在Python中,我們經常會遇到字串的拼接問題,在這裡我總結了四種字串的拼接方式
1.使用%進行拼接
如下
name = input("Please input your name: ")
age = input("Please input your age: ")
job = input("Please input your job: ")
sex = input("Please input your sex: ")
information = '''
----------information %s --------------
Name:%s
Age:%s
Job:%s
Sex:%s
'''%(name, name, age, job, sex)
print(information)
輸出結果如下:
----------information li --------------
Name:li
Age:22
Job:it
Sex:nan
2.使用加號(+)號進行拼接
加號(+)號拼接是我第一次學習Python常用的方法,我們只需要把我們要加的拼接到一起就行了,不是變數的使用單引號或雙引號括起來,是變數直接相加就可以,但是我們一定要注意的是,當有數字的時候一定要轉化為字串格式才能夠相加,不然會報錯
name = input("Please input your name: ")
age = input("Please input your age: ")
job = input("Please input your job: ")
sex = input("Please input your sex: ")
information = '''
----------information '''+name +''' --------------
Name:'''+name +'''
Age:'''+age+'''
Job:'''+job +'''
Sex:'''+sex +'''
'''
print(information)
輸出結果如下:
----------information li --------------
Name:li
Age:22
Job:it
Sex:nan
3.使用字典型別進行拼接
name = input("Please input your name: ")
age = input("Please input your age: ")
job = input("Please input your job: ")
sex = input("Please input your sex: ")
information = '''
----------information {0} --------------
Name:{0}
Age:{1}
Job:{2}
Sex:{3}
'''.format(name, age, job, sex)
print(information)
輸出結果如下:
----------information li --------------
Name:li
Age:24
Job:it
Sex:nan
4.賦值法拼接
name = input("Please input your name: ")
age = input("Please input your age: ")
job = input("Please input your job: ")
sex = input("Please input your sex: ")
information = '''
----------information {_name} --------------
Name:{_name}
Age:{_age}
Job:{_job}
Sex:{_sex}
'''.format(_name=name, _age=age, _job=job, _sex=sex)
print(information)
輸出結果如下:
----------information li --------------
Name:li
Age:24
Job:it
Sex:nan