-
输入一个字符串,打印所有奇数位上的字符(下标是1,3,5,7…位上的字符)
例如: 输入**'abcd1234 ’ ** 输出**‘bd24’**
str1 = 'abcd1234' print(str1[1::2])
-
输入用户名,判断用户名是否合法(用户名长度6~10位)
user_name = input('请输入用户名(6~10位):')
if not 6 <= len(user_name) <= 10:
print('用户名不合法')
else:
print('用户名可用')
-
输入用户名,判断用户名是否合法(用户名中只能由数字和字母组成)
例如: ‘abc’ — 合法 ‘123’ — 合法 ‘abc123a’ — 合法
user_name = input('请输入用户名:') for i in user_name: if not ('0' <= i <= '9' or 'a' <= i <= 'z' or 'A' <= i <= 'Z'): print('用户名不可法') break else: print('合法')
-
输入用户名,判断用户名是否合法(用户名必须包含且只能包含数字和字母,并且第一个字符必须是大写字母)
例如: ‘abc’ — 不合法 ‘123’ — 不合法 ‘abc123’ — 不合法 ‘Abc123ahs’ — 合法
user_name = input('请输入用户名:') if 'A' <= user_name[0] <= 'Z': count = 0 for i in user_name[1:]: if not ('0' <= i <= '9' or 'a' <= i <= 'z' or 'A' <= i <= 'Z'): print('用户名不合法') break else: if '0' <= i <= '9': count += 1 else: if count != 0: print('用户名合法') else: print('用户名不合法') else: print('用户名不合法')
-
输入一个字符串,将字符串中所有的数字字符取出来产生一个新的字符串
例如:输入**‘abc1shj23kls99+2kkk’** 输出:'123992’
str5 = input('输入字符串:') new_str5 = '' for i in str5: if '0' <= i <= '9': new_str5 += i print(new_str5)
-
输入一个字符串,将字符串中所有的小写字母变成对应的大写字母输出 (用upper方法和自己写算法两种方式实现)
例如: 输入**‘a2h2klm12+’ ** 输出 'A2H2KLM12+'
str6 = 'a2h2klm12+' print(str6.upper()) str7 = '' for i in str6: if 'a' <= i <= 'z': i = chr(ord(i) - 32) str7 += i else: str7 += i print(str7)
-
输入一个小于1000的数字,产生对应的学号
例如: 输入**‘23’,输出’py1901023’** 输入**‘9’, 输出’py1901009’** 输入**‘123’,输出’py1901123’**
str7 = 'py1901' str8 = input('输入一个数字(小于1000):') study_id = str7+(3-len(str8))*'0'+str8 print(study_id)
-
输入一个字符串,统计字符串中非数字字母的字符的个数
例如: 输入**‘anc2+93-sj胡说’** 输出:4 输入**’===’** 输出:3
str_1 = input('输入一个字符串:') count = 0 for i in str_1: if not ('0' <= i <= '9' or 'a' <= i <= 'z' or 'A' <= i <= 'Z'): count += 1 print(count)
-
输入字符串,将字符串的开头和结尾变成’+’,产生一个新的字符串
例如: 输入字符串**‘abc123’, 输出’+bc12+’**
str_2 = input('输入一个字符串:') new_str_2 = '+' + str_2[1:-1] + '+' print(new_str_2)
-
输入字符串,获取字符串的中间字符
例如: 输入**‘abc1234’** 输出:‘1’ 输入**‘abc123’** 输出**‘c1’**
str_3 = input('输入一个字符串:')
new_str = ''
if len(str_3) % 2:
new_str += str_3[int(len(str_3)/2)]
else:
new_str += str_3[int(len(str_3)/2-1)]
new_str += str_3[int(len(str_3) / 2)]
print(new_str)
- 写程序实现字符串函数find/index的功能(获取字符串1中字符串2第一次出现的位置)
例如: 字符串1为:how are you? Im fine, Thank you! , 字符串2为:you, 打印8
str_4 = 'how are you? Im fine, Thank you!'
str_5 = 'you'
print(str_4.index(str_5))
str_4 = 'how are you? Im fine, Thank you!'
str_5 = 'you'
print(str_4.find(str_5))
- 获取两个字符串中公共的字符
例如: 字符串1为:abc123, 字符串2为: huak3 , 打印:公共字符有:a3
str1 = 'abc123'
str2 = 'huak3'
str3 = ''
for x in str1:
for y in str2:
if x == y:
str3 += x
print(str3)