python2.7的字符串拼接
方法一:直接字符串拼接
# -*- coding: UTF-8 -*-
# 开发人:李柏霖
# 开发时间:2021/7/21 10:32
name = raw_input("Name:")
age = raw_input("Age:")
job = raw_input("job:")
salary = raw_input("salary:")
info = '''
"------info of ''' + name + '''------"
Name:''' + name + '''
Age:''' + age + '''
job:''' + job + '''
salary:''' + salary + '''
'''
输出结果:
方法二:使用占位符
# -*- coding: UTF-8 -*-
# 开发人:李柏霖
# 开发时间:2021/7/21 10:32
name = raw_input("Name:")
age = raw_input("Age:")
job = raw_input("job:")
salary = raw_input("salary:")
info3='''
——————————————————————————————占位符 %s——————————————————————————————
Name:%s
Age:%s
Job:%s
Salary:%s
'''%(name,name,age,job,salary)
print info3
输出结果:
字符串类型转换
# -*- coding: UTF-8 -*-
# 开发人:李柏霖
# 开发时间:2021/7/21 10:32
name = raw_input("Name:")
age = raw_input("Age:")
job = raw_input("job:")
salary = raw_input("salary:")
info3='''
——————————————————————————————占位符 %s——————————————————————————————
Name:%s
Age:%d
Job:%s
Salary:%s
'''%(name,name,age,job,salary)
print info4
报错:
TypeError: %d format: a number is required, not str
原因分析:
输入的都是字符串类型,我们转换一下格式就可以了。
合拼为一句:
age = int(raw_input("Age:"))
占位符拼接
方法一:
# -*- coding: UTF-8 -*-
# 开发人:李柏霖
# 开发时间:2021/7/21 10:32
name = raw_input("Name:")
age = int(raw_input("Age:"))
job = raw_input("job:")
salary = raw_input("salary:")
info5='''
——————————————————————————————占位符 {name5}——————————————————————————————
Name:{name5}
Age:{age5}
Job:{job5}
Salary:{salary5}
'''.format(name5=name,age5=age,job5=job,salary5=salary)
效果一样:
方法二:
name = raw_input("Name:")
age = int(raw_input("Age:"))
job = raw_input("job:")
salary = raw_input("salary:")
info6='''
——————————————————————————————占位符 {0}——————————————————————————————
Name:{0}
Age:{1}
Job:{2}
Salary:{3}
'''.format(name,age,job,salary)
print info6