Concatenating (joining) strings in Python is very simple comparing to other programming languages. You can write two strings directly next to each other in the following format:
string_id = "str_1" "str_2"
<string_id represents the string variable name after concatenation, str_1 and str_2 are the contents of the string to be concatenated. Using this notation, Python will automatically join two strings together.
[Example] Concatenate strings in the form of continuous writing:
string_1 = "Welcome to" "Free Learning Points" print(string_1) string_2 = "addition" "subtraction" "multiplication" "division" print(string_2)
The output is:
Welcome toFree Learning Points
additionsubtractionmultiplicationdivision
It should be noted that this writing method can only concatenate string constants.
If you need to concatenate variables, you must use the + operator to join them together, the specific format is:
string_id = string_1 + string_2
Of course, the + operator can also concatenate string constants.
[Example] Use + operator to concatenate strings:
string_1= "Hello," string_2 = "Free Learning Points" string_id = string_1 + "welcome to" + string_2 print(string_id)
The output is:
Hello, welcome to Free Learning Points
In many application scenarios, we need to join strings and numbers together, and Python does not allow direct joining of numbers and strings, so we must first convert numbers to strings. Numbers can be converted to strings with the help of the str() and repr() functions, which are used in the format:
str(obj)
repr(obj)
obj represents the object to be converted. It can be numbers, lists, tuples, dictionaries, and other types of data.
Look at the following code:
name = "Alice" age = 18 data = name + " is " + str(age) + " years old." print(data)
The output is:
Alice is 18 years old.
Although str () and repr () can both convert numbers to strings, there are differences between them:
Consider the following example:
a = "www.freelearningpoints.com" a_string = str(a) a_repr = repr(a) print(type(a_string)) print(a_string) print(type(a_repr))
The output is:
[class 'str']
www.freelearningpoints.com
[class 'str']
www.freelearningpoints.com
In this example, a is itself a string, but we still converted it using str() and repr(). It can be seen from the running results that str() retains the original appearance of the string, and repr() uses quotation marks to surround the string. This is the Python string expression form.
In addition, when an expression (variable, addition, subtraction, multiplication, division, logical operation, etc.) is entered in the Python interactive programming environment, Python automatically uses the repr () function to process the expression.
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises