Three methods of String concatenation in Python: python merge and merge
In Python, we often encounter the problem of String concatenation. Here I summarize the following three String concatenation methods:
1. Splice with the plus sign (+)
The plus sign (+) concatenation is the first time I learned a common method for Python. We only need to splice the concatenation we want to add together, instead of using single or double quotation marks for variables, the variable can be directly added, but we must note that when there is a number, it must be converted to the string format to add, 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 result is as follows:
Information of Alex:
Name: Alex
Age: 38
Sex: girl
String concatenation can be directly added, which is easier to understand, but you must remember that variables are directly added, not variables that must be caused by quotation marks. Otherwise, errors may occur, in addition, numbers must be converted to strings before they can be added. Remember that numbers cannot be directly added.
2. Splice with %
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 result is as follows:
Information of Alex:
Name: Alex
Age: 38
Sex: girl
The second method is to use the % sign method. We will add the variables in a uniform manner later, which avoids the use of the plus sign and makes the code shorter. I like this method too, it is simple and convenient. You only need to know what information you need, set the format in it, and add the variable.
3. Use single quotation marks (''') or double quotation marks (")
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 result is as follows:
Information of Alex:
Name: Alex
Age: 38
Sex: girl
You can use either single quotation marks (''') or double quotation marks ("). This method is also very convenient. We first define it, I think these three methods are quite good when defining the formats we need.