Three ways of string splicing in Python

In Python, we often encounter string splicing problems. Here I summarize three string splicing methods:

1. Use the plus (+) sign for stitching

The plus sign (+) sign splicing is a common way for me to learn Python for the first time. We just need to splice the things we want to add together. If the variables are not variables, use single or double quotes to enclose them, just add variables directly. Yes, but we must pay attention to that when there are numbers, they must be converted to string format to be able to be added, otherwise an error will be reported.

name = input("Please input your name: ")
age = input("Please input your age: ")
sex = input("Please input your sex: ")

print("Information of " + name + ":" + "\n\tName:" + name + "\n\tAge:" + age + "\n\tSex:" + sex)

The output is as follows:

Information of Alex:
    Name:Alex
    Age:38
    Sex:girl

String splicing can be added directly, which is easier to understand, but it must be remembered that variables are added directly, not variables must be enclosed in quotation marks, otherwise errors will occur. In addition, numbers must be converted to strings to be able to be added. Yes, it must be remembered that you cannot add numbers directly.

2. Use% for stitching

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
name = input("Please input your name: ")
age = input("Please input your age: ")
sex = input("Please input your sex: ")

print("Information of \n\tName:%s\n\tAge:%s\n\tSex:%s" %(name,age,sex))

The output is as follows:

Information of Alex:
    Name:Alex
    Age:38
    Sex:girl

The second way is to use the% sign method. We will add the variables uniformly later. This avoids the use of the plus sign and can make the code shorter. I also like this way, simple and convenient, as long as you know what you need What kind of information it is, set the format in it, and then add the variables.

3. Use single quotation marks (``'''') or double quotation marks ("""""")

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
name = input("Please input your name: ")
age = input("Please input your age: ")
sex = input("Please input your sex: ")

message = '''
Information of %s:
Name:%s
Age:%s
Sex:%s
'''%(name,name,age,sex)
print(message)

The output is as follows:

Information of Alex:
    Name:Alex
    Age:38
    Sex:girl

Use single quotation marks ("'''') or double quotation marks (""""""). This method is also very convenient. We first define, define the format we need, and try these frequently. I think these three methods are quite good.

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/109050593