时隔五年,突然又想起这里,放不下的就重新开始吧。
非常的入门级别,给自己当笔记了。
小甲鱼的一道课后题:验证用户密码,只有三次输错机会,内容包含*则不计算在内。
思路一:设置3次机会,初始化密码为‘7878’,输入‘*’时提示不可以。
count = 3password= '7878'
whilecount:print('Chance.',3-count+1)
passwd= input('Please input your password:')if passwd ==password:print("OK,welcome enter the program!")break
elif '*' inpasswd:print('It\'s unallowed has * in password.')
count-= 1
continue
else:print('Sorry,that\'s wrong,')
count-= 1
运行结果:
Chance. 1
Please input your password:78
Sorry,that's wrong,
Chance. 2
Please input your password:7*8
It's unallowed has * in password.
Chance. 3
Please input your password:7878
OK,welcome enter the program!
思路二:
后来又觉得可以这样理解,如果输入*,虽提示不可以,但程序自动不计算(即忽略*)进行匹配,那么就要想办法把字符串里的“*”剔除,字符串不可变,列表里的元素可变,把字符串转换成列表后去掉*号,最笨的时候想到用for语句依个匹配是否为*,如果是就删掉,python列表有个remove方法,可直接删除指定元素,完全不要for语句一个个去对比了,我真是对自己感到抱歉:
count = 3password= list('7878')whilecount:print('Chance.',3-count+1)
passwd= list(input('Please input your password:'))if '*' inpasswd:#print('It\'s unallowed has * in password.')
passwd.remove('*')if passwd ==password:print("OK,welcome enter the program!")break
else:print('Sorry,that\'s wrong,')
count-= 1
运行结果:
Chance. 1Please input your password:78*78OK,welcome enter the program!
思路三:那如果不转换成列表呢,有没有办法?当然有,replace直接对字符串下手
#replace方法把字符串中的*去掉
count = 3password= '7878'
whilecount:print('Chance.',3-count+1)
passwd= input('Please input your password:')
newpasswd= passwd.replace('*','')if newpasswd ==password:print("OK,welcome enter the program!")break
else:print('Sorry,that\'s wrong~')
count-= 1
运行结果:
Chance. 1Please input your password:222Sorry,that's wrong~
Chance. 2Please input your password:78*7*8OK,welcome enter the program!
最后分享分享~上网查到一篇帖子总结了
https://www.cnblogs.com/zhouzhiyao/p/11498907.html(感谢,原文链接必须奉上)
分析
在Python中,字符串是不可变的。所以无法直接删除字符串之间的特定字符。
所以想对字符串中字符进行操作的时候,需要将字符串转变为列表,列表是可变的,这样就可以实现对字符串中特定字符的操作。
1、删除特定字符
特定字符的删除,思路跟插入字符类似。
可以分为两类,删除特定位置的字符 或者删除指定字符。
1.1、删除特定位置的字符
使用.pop()方法。可输入参数,即为要删除的索引。
例如:list_str.pop(1)
1.2、删除指定字符
删除指定字符与删除特定位置的区别是:删除指定字符,需要提供指定的字符,和需要删除的最大数目。而删除特定位置的字符,只需要提供删除字符的索引即可。
1.3、两种实现
删除的实现,除了像pop方法那种,弹出特定字符的删除,也可以用空字符来替换特定的字符,来实现删除。
.replace()方法
replace(...) method of builtins.str instance
S.replace(old, new[, count]) -> str
比如,上面我使用的方法。
注意,它返回的是替换后(在这种情况下,是删除字符)的字符,没有改变原始字符串,所以如果想使用替换后的字符,需要指定一个变量进行赋值。
眼尖的你,发现还有一个可选参数,count。
count参数就可以指定要替换几个。我们无意中知道了如何删除指定数目的字符,可以替换0个,默认全部替换。
正则表达式
除了使用Python标准库中的方法,还可以使用re正则表达式库,来实现。
使用re.sub()方法,这个方法的功能更强大,可以替换特定模式的字符。
因为模式匹配比较麻烦,所以比较强大。
sub(pattern, repl, string, count=0, flags=0)
pattern代表指定的模式,这是强大的原因,如果简单点使用,只指定特定字符,就可以用'特定字符'来表示模式。
repl代表的是,需要替换成的字符,如果删除,就是替换成空字符。
string代表的是,需要被替换的字符串。
count是替换的次数。
总结
无论是Python字符串自带的.replace()方法,还是re提供的.sub()方法,都是不改变原来的字符串,返回值才是替换的字符串。所以,如果要使用替换的字符串,就需要将返回值赋值给一个变量。
这两种方法,默认都是替换所有的指定字符。