1.字符串倒序输出
代码实现
import string
def is_reverse_abnormal_string(zxc):
if zxc == "":#判断空
print("empty input!")
return False
else:#过滤非法字符串,字母大小写除外
for i in range(0,len(zxc)):#遍历,用空格替换非法字符串
zxc=list(zxc)
if zxc[i] not in (string.ascii_letters+" "):
zxc[i]=" "
#按照空格slit,最后倒序输出
# print(zxc)
zxc_join="".join(zxc)
# print(zxc_join)
zxc=str(zxc_join)
#print(zxc)
zxc_split=zxc.split() #以空格为分割符
#print(zxc_split)
zxc_reverse=zxc_split[::-1]
zxc_result=" ".join(zxc_reverse)
#zxc_reverse=zxc_split.reverse()
#print(zxc_reverse)
print("zxc_reverse is '{0}' ".format(zxc_result))
return True
if __name__ == "__main__":
while True:
print ("Please enter a abnormal string:")
abnormal_string=input()
is_reverse_abnormal_string(abnormal_string)
运行结果:
总结:
关键点:
- 非法字符串替换
- 字符串和列表转换,字符串不能修改内容,str() list()
- 列表拼接 join()
- 分割 split()
- 列表倒序输出 list[::-1]
列表倒序输出
1.切片-------list[::-1]
2.函数revers对数组-列表进行操作—list.reverse()
3.函数reversed返回一个迭代对象,需要list化—list(reversed(list))
运行截图