格式化输出:name = qjage = 30job = itsalary = 6000例1:字符串拼接方法,不建议,因为会在内存中开辟多块内存空间。 info = ‘‘‘---------- info of ‘‘‘ + name + ‘‘‘ ---------Name:‘‘‘ + name + ‘‘‘Age:‘‘‘ + age + ‘‘‘job:‘‘‘ + job + ‘‘‘Salary:‘‘‘ + salary 例2:使用%s、%d、%f占位info = ‘‘‘---------- info of %s ---------Name:%sAge:%djob:%sSalary:%d‘‘‘ % (name,name,age,job,salary)print(info)%s:代表字符串%d:代表整数(需强制相关变量为整数类型)%f:代表浮点即小数(需强制相关变量为浮点类型)打印变量类型:print(type(变量名))强制转换变量类型为整形:age = int(input(age))强制转换变量类型为字符串:age = str(input(age)) 例3:使用{}占位(官方建议使用此方式)info = ‘‘‘---------- info of {_name} ---------Name:{_name}Age:{_age}job:{_job}Salary:{_salary}‘‘‘ .format(_name = name,_age = age,_job = job,_salary = salary)print(info) 例4:使用{}占位,花括号中不指定参数info = ‘‘‘---------- info of {0} ---------Name:{0}Age:{1}job:{2}Salary:{3}‘‘‘ .format(name,age,job,salary)print(info)
原文地址:https://www.cnblogs.com/yitianyouyitian/p/9267450.html
时间: 2024-10-16 19:25:38