How can we combine two string variables in Python?

To combine two string variables together, you can use the string concatenation operator “+”, as shown below:

str1 = "Hello"
str2 = "World"
result = str1 + str2

print(result)  # 输出:HelloWorld

You can also use the join() method of strings to merge multiple strings into one, as shown below:

str1 = "Hello"
str2 = "World"
result = ''.join([str1, str2])

print(result)  # 输出:HelloWorld

Furthermore, you can also combine the two strings using f-string or formatted string, as shown below:

str1 = "Hello"
str2 = "World"
result = f"{str1}{str2}"

print(result)  # 输出:HelloWorld

It should be noted that in these examples, two strings are directly concatenated together. If you need to add other characters or spaces between two strings, you can include them when concatenating. For example, result = str1 + ” ” + str2 or result = f”{str1} {str2}”.

bannerAds