python学习(三)字符串格式化&strip的用法&小练习

1、字符串格式化

输出内容是几个字符串进行拼接时,有以下两种方式:

1)采用+进行字符串拼接

import datetime
today = datetime.date.today()
username = input('请输入用户名:')
welcome = '欢迎光临:'+username+str(today)
print (welcome)
2)使用占位符
import datetime
today = datetime.date.today()
username = input('请输入用户名:')
welcome = '欢迎光临:%s 今天日期是:%s'%(username,today) #用占位符,多个参数
print (welcome)
PS:%s 字符串 %d 整数  %.2f 保留两位小数
username = input('请输入用户名:')
age = 18
score = 98.656
info = '你的用户名是:%s,年龄是%d,成绩是%.2f'%(username,age,score)
print(info)
2、strip 去空格
strip的作用是在输入账号密码的时候去掉你输入数据中最前面或者最后面的空格

小练习:

写一个登录程序,让用户输入账号和密码,输入用户和密码输入正确的话,提示你  xxx,欢迎登录,今天的日期是xxx,程序结束。

错误的话,提示账号/密码输入错误, 最多输入3次,如果输入3次都没有登录成功,提示失败次数过多。需要判断输入是否为空,输入空也算输入错误一次。

用while循环或者for循环都可以

while循环

import datetime
name = '刘佳'
passwd = 'As123456'
count = 0
date = datetime.date.today()
while count < 3:
new_name = input('请输入用户名:').strip()
new_passwd = input('请输入密码:').strip()
if new_name =='' or new_passwd == '':
print('用户名密码不能为空!')
elif new_name == name and new_passwd == passwd:
welcome = '欢迎登录 %s,今天的日期是%s' % (name, date)
print(welcome)
break
else:
print('用户名/密码输入错误!')
count += 1
else:
print('输入错误次数过多,今日无法再输入!')

for循环:

import datetime
name = '刘佳'
passwd = 'As123456'
date = datetime.date.today()
for i in range(3):
new_name = input('请输入用户名:').strip()
new_passwd = input('请输入密码:').strip()
if new_name =='' or new_passwd == '':
print('用户名密码不能为空!')
elif new_name == name and new_passwd == passwd:
welcome = '欢迎登录 %s,今天的日期是%s' % (name, date)
print(welcome)
break
else:
print('用户名/密码输入错误!')
else:
print('输入错误次数过多,今日无法再输入!')
 
 
原文地址:https://www.cnblogs.com/emilyliu/p/8647529.html