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