-
输入一个字符串,打印所有奇数位上的字符(下标是1,3,5,7…位上的字符)
例如: 输入 'abcd1234 ’ 输出 'bd24’
str1 = input('输入一串字符:') for index in range(1, len(str1),2): print(str1[index], end="")
-
输入用户名,判断用户名是否合法(用户名长度6~10位)
pw = input('请输入用户名(用户名长度6~10位):') if 6 <= len(pw) <= 10: print('用户名合法’) else: print('用户名不合法')
-
输入用户名,判断用户名是否合法(用户名中只能由数字和字母组成)
例如: ‘abc’ — 合法 ‘123’ — 合法 ‘abc123a’ — 合法
pw = input('请输入用户名(字母和数字组成):') for c in pw: if not ('0' <= c <= '9' or 'A' <= c <= 'Z' or 'a' <= c <= 'z'): print('用户名不合法') break else: print('用户名合法')
-
输入用户名,判断用户名是否合法(用户名必须包含且只能包含数字和字母,并且第一个字符必须是大写字母)
例如: ‘abc’ — 不合法 ‘123’ — 不合法 ‘abc123’ — 不合法 ‘Abc123ahs’ — 合法
user_name = input('请输入用户名(字母和数字组成):') if 'A' <= user_name[0] <= 'Z': count = 0 for c in user_name: if not ('0' <= c <= '9' or 'A' <= c <= 'Z' or 'a' <= c <= 'z'): print('用户名不合法') break else: if '0' <= c <= '9': count += 1 else: if count > 0: print('用户名合法') else: print('用户名不合法') else: print('用户名不合法')
-
输入一个字符串,将字符串中所有的数字字符取出来产生一个新的字符串
例如:输入 ‘abc1shj23kls99+2kkk’ 输出:'123992’
pw = input('请输入字符串:') str1 = '' for c in pw: if '0' <= c <= '9': str1 += c print(str)
-
输入一个字符串,将字符串中所有的小写字母变成对应的大写字母输出 (用upper方法和自己写算法两种方式实现)
例如: 输入 ‘a2h2klm12+’ 输出 'A2H2KLM12+'
pw = input('请输入字符串:') for c in pw: if 'a' <= c <= 'z': print(c.upper(), end="") else: print(c, end="")
-
输入一个小于1000的数字,产生对应的学号
例如: 输入 ‘23’,输出 ‘py1901023’ 输入 ‘9’, 输出 ‘py1901009’ 输入 ‘123’,输出 'py1901123’
# 方法一 sid = int(input('请输入学号(小于1000):')) print(f'py1901{sid:0>3d}') # 方法二 num = input('请输入学号(小于1000):') sid = 'py1901' + num .zfill(3) print(sid)
-
输入一个字符串,统计字符串中非数字字母的字符的个数
例如: 输入 ‘anc2+93-sj胡说’ 输出: 4 输入 ‘===’ 输出: 3
pw = input('请输入字符串:') count = 0 for c in pw: if not ('0' <= c <= '9' or 'A' <= c <= 'Z' or 'a' <= c <= 'z'): count += 1 print(count)
-
输入字符串,将字符串的开头和结尾变成’+’,产生一个新的字符串
例如: 输入字符串 ‘abc123’, 输出 '+bc12+'
# 方法一: str = input('请输入字符串:') str1 = '' length = len(str) for index in range(length): if index == 0 or index == length - 1: str1 += '+' else: str1 += str[index] print(str1) # 方法二 str1 = input('请输入字符串:') result = '+' + str1[1:-1] + '+' print(result)
-
输入字符串,获取字符串的中间字符
例如: 输入 ‘abc1234’ 输出: ‘1’ 输入 ‘abc123’ 输出 'c1’
pw = input('请输入字符串:')
length = len(pw)
if length & 1:
print(pw[length // 2])
else:
print(pw[length // 2 - 1:length // 2 + 1])
- 写程序实现字符串函数find/index的功能(获取字符串1中字符串2第一次出现的位置)
例如: 字符串1为:how are you? Im fine, Thank you! , 字符串2为:you, 打印8
str1 = input('请输入字符串:')
str2 = input('查找的字符串:')
l1 = len(str1)
l2 = len(str2)
for i in range(l1 - l2 + 1):
if str1[i:i+l2] == str2:
print(i)
break
else:
print('没找到!')
- 获取两个字符串中公共的字符
例如: 字符串1为:abc123, 字符串2为: huak3 , 打印:公共字符有:a3
str1 = input('请输入字符串1:')
str2 = input('请输入字符串2:')
str3 = ''
for word in str1:
if word in str2 and word not in str3:
str3 += word
print(f'公共字符有:{str3}')