python(字符串str,练习题)

一、字符串的定义

a = 'hello'
b = "westos"
c = 'what\'s'
d = "what's"
e = """
    用户管理系统
    1.添加用户
    2.删除用户
    3.显示用户
    .....
"""

#查看
print(e)
print(type(e))

二、字符串的特性
1.字符串 索引 的概念:
例:
s = ‘hello’

索引:0 1 2 3 4(索引值是从0开始的)
print(s[0])
print(s[4])
print(s[-1]) # 拿出字符串的最后一个字符

切片
print(s[0:3]) # 切片的原则 s[start????step] 从start开始到end-1结束,步长为step
print(s[0:4:2])
print(s[:]) # 显示所有字符
print(s[:3]) # 显示前3个字符
print(s[::-1]) # 字符串的翻转
print(s[1:]) # 除了第一个字符之外,其他全部显示

重复打印
print(s*10)

连接
print('hello ’ + ‘python’)

成员操作符
print(‘he’ in s)
print(‘aa’ in s)
print(‘he’ not in s)

三、字符串常用方法–大小写和数字

>>> 'Hello'.istitle() ##判断某个字符串是否为标题(第一个字母大写,其余字母小写)
True
>>> 'hello'.istitle()
False
 >>> 'hello'.isdigit() ##是否为数字
False
>>> 'hello'.isupper()
False
>>> 'Hello'.isupper()
False
>>> 'HELLO'.isupper()  ##是否为大写
True
>>> 'hello'.upper() ##转换成大写输出
'HELLO'
>>> 'Hello'.islower() ##判断是否为小写
False
>>> 'hello'.islower()
True
>>> 'HELLO'.lower()  ##转换为小写
'hello'
>>> 'hello'.title() ##转换为标题
'Hello'
  >>> '123hello'.isalnum() ##判断是否为字母和数字
True
  >>> 'hello'.isalpha()  ##判断是否为字母
True

四、字符串开头和结尾的匹配

filename = 'hello.log'
if filename.endswith('.log'):   ##看结尾是否匹配
    print(filename)
else:
    print('error.file')

url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'https://172.25.254.250/index.html'

if url3.startswith('http://'):  ##看开头是否匹配
    print('爬取网页')
else:
    print('不能爬取网页')

五、字符串去除两边的空格
注意:去除左右两边的空格,空格为广义的空格 包括:\n \t

>>> s = '      hello     '
>>> s
'      hello     '
>>> s.lstrip()  ##去除左边空格
'hello     '
>>> s.rstrip()  ##去除右边空格
'      hello'

>>> s = '\n\thello     '
>>> s
'\n\thello     '
>>> s.strip()  ##去除空格,同时去除\n与\t
'hello'
>>> s = 'helloh'
>>> s.strip('h')   ##去除制定内容
'ello'
>>> s.strip('he')
'llo'
>>> s.lstrip('he') ##去除左边指定内容
'lloh'
>>>

六、字符串的对齐

print('学生管理系统'.center(30))
print('学生管理系统'.center(30,'*'))
print('学生管理系统'.center(30,'@'))
print('学生管理系统'.ljust(30,'*'))
print('学生管理系统'.rjust(30,'*'))

python(字符串str,练习题)
七、字符串的搜索和替换

s = 'hello world hello'

#find找到子字符串,并返回最小的索引
print(s.find('hello'))
0
print(s.find('world'))
6

#找到子串,并返回最大索引
print(s.rfind('hello'))
12

#替换字符串中的'hello' 为'westos'
print(s.replace('hello','westos'))
westos world westos

八、字符串的统计
print(‘hello’.count(‘l’)) ##统计l出现的次数
2
print(‘hello’.count(‘ll’)) ##统计ll出现的次数
1
print(len(‘hello’)) ##统计hello的长度
5

九、字符串的分离和链接

s = '172.52.254.250'
s1 = s.split('.')  ##以 . 分离
print(s1)
	['172','25','254','250']
print(s1[::-1])  ##以倒序打印出
	['250','254','25','172']
	
date = '2019-03-13'
date1 = date.split('-')  ##以- 分离
print(date1)
	['2019','03','13']
	
#连接,通过指定的连接符,连接每个字符串
print(''.join(date1))  ##直接链接
	20190313
print('/'.join(date1))
	2019-03-13
print('@'.join('hello'))
	[email protected]@[email protected]@o

十、字符串练习
(1)判断一个整数是否是回文数。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

##示例:
示例 1:
输入: 121
输出: true

示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数

num = input('Num:')
if num == num[::-1]:  ##看它倒着输出与正着输出是否相等
	print('这是一个回文数')
else:
	print('这不是一个回文数')

(2)变量名是否合法:
1.变量名可以由字母,数字或者下划线组成
2.变量名只能以字母或者下划线开头
s = ‘[email protected]

1.判断变量名的第一个元素是否为字母或者下划线 s[0]
2.如果第一个元素符合条件,判断除了第一个元素之外的其他元素s[1:]

#1.变量名的第一个字符是否为字母或下划线
#2.如果是,继续判断 ---->4
#3.如果不是,报错
#4.依次判断除了第一个字符之外的其他字符,是否为字母数字或下划线

while True:
    s = input('变量名:')
    if s == 'exit':
        print('退出')
        break
    if s[0].isalpha() or s[0] == '_':
        for i in s[1:]:
            if not(i.isalnum() or i == '_'):
                print('%s变量名不合法' %(s))
                break
        else:
            print('%s变量名合法' %(s))
    else:
        print('%s变量名不合法' %(s))

(3)小米笔试编程题目(作业)

  • 题目描述:
    给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前>后没有空格。
    比如: (1) “hello xiao mi”-> “mi xiao hello”
  • 输入描述:
    输入数据有多组,每组占一行,包含一个句子(句子长度小于1000个字符)
  • 输出描述:
    对于每个测试示例,要求输出句子中单词反转后形成的句子

示例1:
输入
hello xiao mi
输出
mi xiao hello

解:

print(' '.join(input().split()[::-1]))
##input().split()---->将输入的字符串按空格分离成单独的字符串
##[::-1]---->将字符串倒着打印
##' '.join()--->并以空格链接

python(字符串str,练习题)
(4)

  1. 设计一个程序,帮助小学生练习10以内的加法
    详情:
    - 随机生成加法题目;
    - 学生查看题目并输入答案;
    - 判别学生答题是否正确?
    - 退出时, 统计学生答题总数,正确数量及正确率(保留两位小数点);
    解:
import random 
count = 0 
right = 0 

while True: 
	a= random.randint(0,9) 
	b= random.randint(0,9) 
	print('%d + %d = ' %(a,b)) 
	question = input('请输入您的答案:(q退出)') 
	result = a + b 
	if question == str(result): 
		print('回答正确') 
		right += 1 
		count += 1 
	elif question == 'q': 
		break 
	else: 
		print('回答错误') 
		count += 1 
percent = right / count 
print('测试结束,共回答%d道题,正确个数为%d,正确率为%.2f%%‘%(count,right,percent * 100))
  1. 小学生算术能力测试系统:
    设计一个程序,用来实现帮助小学生进行百以内的算术练习,
    它具有以下功能:
    提供10道加、减、乘或除四种基本算术运算的题目;
    练习者根据显示的题目输入自己的答案,
    程序自动判断输入的答案是否正确并显示出相应的信息。

import random
op = [’+’,’-’,’*’,’/’]
print(random.choice(op))

import random

count = 0
right = 0

while True: 
	a = random.randint(0, 9) 
	# 作为除数 
	b = random.randint(1, 9) 
	op = ['+', '-', '*', '//'] 
	d = random.choice(op) 
	print('%d %s %d = ' % (a, d, b)) 
	question = input('请输入您的答案: (q退出)') 
	result1 = a + b 
	result2 = a - b 
	result3 = a * b 
	result4 = a // b 
	if question == str(result1): 
		print('回答正确') 
		right += 1 
		count += 1 
	elif question == str(result2): 
		print('回答正确') 
		right += 1 
		count += 1 
	elif question == str(result3): 
		print('回答正确') 
		right += 1 
		count += 1 
	elif question == str(result4): 
		print('回答正确') 
		right += 1 
		count += 1 
	elif question == 'q': 
		break 
	else: 
		print('回答错误') 
		count += 1 
 percent = right / count 
 print('测试结束,共回答%d道题,正确个数为%d,正确率为%.2f%%' % (count, right, percent * 100))