上章我們講完了strip的功能,這章我們來看看strip的應(yīng)用。
還記不記得我們之前學(xué)過的模擬QQ登入的案例。
username = '110119'
password = '123456'
num = 0
for i in range(3):
input_username = input('請輸入你的賬號(hào):')
input_password = input('請輸入你的密碼:')
if input_username == username and input_password== password:
print("登入成功")
while True:
action = input('請輸入你的操作')
if action == 'q':
break
print(f'正在看{action}')
break
else:
print('用戶名或密碼錯(cuò)誤,請注意格式大小寫')
num += 1
else:
print('賬號(hào)密碼輸錯(cuò)三次,已被鎖定')
這是之前學(xué)for循環(huán)的代碼。
如果用戶輸入賬號(hào)密碼的時(shí)候,有的用戶賬號(hào)很多,密碼是復(fù)制過來的,復(fù)制的時(shí)候多了一個(gè)空格,那么就會(huì)直接提示錯(cuò)誤?;蛘呤侄读艘幌?,碰到了空格鍵,都會(huì)導(dǎo)致輸入錯(cuò)誤。
最后用戶說了一句,垃圾軟件,直接卸載了。
我們在寫代碼的時(shí)候,要將用戶當(dāng)成傻子一樣,讓用戶用傻瓜似的操作,幫用戶規(guī)避這種問題。
我們看上面的代碼,input會(huì)將用戶輸入的賬號(hào)密碼保存成字符串,返回到當(dāng)前位置。字符串可以點(diǎn)strip對吧。
既然input本身返回的就是字符串類型,我那么我們就直接在括號(hào)后面加上點(diǎn)strip功能。
username = '110119'
password = '123456'
num = 0
for i in range(3):
input_username = input('請輸入你的賬號(hào):').strip()
input_password = input('請輸入你的密碼:').strip()
if input_username == username and input_password== password:
print("登入成功")
while True:
action = input('請輸入你的操作')
if action == 'q':
break
print(f'正在看{action}')
break
else:
print('用戶名或密碼錯(cuò)誤,請注意格式大小寫')
num += 1
else:
print('賬號(hào)密碼輸錯(cuò)三次,已被鎖定')
我們試試將賬號(hào)密碼增加空格,看看還會(huì)不會(huì)提示錯(cuò)誤。
看!最后我輸入那么長的空格都顯示輸入正確!
最后還是想提醒一下,strip返回的是字符串的功能,不是變量名的功能!
未經(jīng)允許不得轉(zhuǎn)載:445IT之家 » Python 字符符串詳解之strip函數(shù)應(yīng)用