-
输入一个字符串,打印所有奇数位上的字符(下标是1,3,5,7…位上的字符)
例如: 输入**'abcd1234 ’ ** 输出**‘bd24’**
string = 'abcd1234' print(string[1::2])
-
输入用户名,判断用户名是否合法(用户名长度6~10位)
if 6 <= len(strings) <= 10: print('合法') else: print('不合法')
-
输入用户名,判断用户名是否合法(用户名中只能由数字和字母组成)
例如: ‘abc’ — 合法 ‘123’ — 合法 ‘abc123a’ — 合法
strings = 'abcd1234' if any(c for c in strings if not ('a' <= c <= 'z' or '0' <= c <= '9')): print('不合法') else: print('合法')
-
输入用户名,判断用户名是否合法(用户名必须包含且只能包含数字和字母,并且第一个字符必须是大写字母)
例如: ‘abc’ — 不合法 ‘123’ — 不合法 ‘abc123’ — 不合法 ‘Abc123ahs’ — 合法 ‘Abc’ — 不合法
if not 'A' <= strings[0] <= 'Z': print('不合法') elif any(c for c in strings[1::] if not ('a' <= c <= 'z' or '0' <= c <= '9')): print('不合法') else: print('合法')
-
输入一个字符串,将字符串中所有的数字字符取出来产生一个新的字符串
例如:输入**‘abc1shj23kls99+2kkk’** 输出:‘123992’
new_strings = '' for c in strings: if '0' <= c <= '9': new_strings += c print(new_strings)
-
输入一个字符串,将字符串中所有的小写字母变成对应的大写字母输出 (用upper方法和自己写算法两种方式实现)
例如: 输入**‘a2h2klm12+’ ** 输出 ‘A2H2KLM12+’
up_strings = strings.upper() new_strings = '' for c in strings: if 'a' <= c <= 'z': new_strings += chr(ord(c)-32) else: new_strings += c print(new_strings) print(up_strings)
-
输入一个字符串,统计字符串中非数字非字母的字符的个数
例如: 输入’anc2+93-sj胡说’ 输出:4 输入**‘===’** 输出:3
strings = "anc2+93-sj胡说" count = 0 for c in strings: if not ('a' <= c <= 'z' or '0' <= c <= '9' or 'A' <= c <= 'Z'): count += 1 print(count)
-
输入字符串,将字符串的开头和结尾变成’+',产生一个新的字符串
例如: 输入字符串**‘abc123’, 输出’+bc12+'**
new_strings = '+' for i in range(1,len(strings)-1): new_strings += strings[i] new_strings += '+' print(new_strings)
-
输入字符串,获取字符串的中间字符
例如: 输入**‘abc1234’** 输出:‘1’ 输入**‘abc123’** 输出**‘c1’**
strings = 'abc123' length = len(strings) print(strings[length//2-1:length//2+1] if length % 2 == 0 else strings[length//2])
-
写程序实现字符串函数find/index的功能(获取字符串1中字符串2第一次出现的位置)
例如: 字符串1为:how are you? Im fine, Thank you! , 字符串2为:you, 打印8
暂时先不做 暂时先不做 暂时先不做
-
获取两个字符串中公共的字符
例如: 字符串1为:abcaaa123, 字符串2为: huak3 , 打印:公共字符有:a3
strings1 = 'abcaaa123'
strings2 = 'huak3'
cmped_str = ''
same_str = ''
for c in strings1:
if c in (cmped_str or same_str):
pass
else:
cmped_str += c
for s in strings2:
if c == s:
same_str += c
break
print(same_str)