How to concatenate strings in Python - Biz Tech

How to concatenate strings in Python

Listen

In Python, you can concatenate strings using the + operator or the join() method.

Here’s an example of concatenating two strings using the + operator:

first_name = "John"<br />
last_name = "Doe"</p>
<p>full_name = first_name + " " + last_name</p>
<p>print(full_name) # Output: "John Doe"

In this example, we’ve created two string variables, first_name and last_name, and concatenated them together using the + operator. We’ve also added a space character between the two names.

Here’s an example of concatenating multiple strings using the join() method:

words = ["Hello", "world", "!"]</p>
<p>sentence = " ".join(words)</p>
<p>print(sentence) # Output: "Hello world !"

In this example, we’ve created a list of string variables called words. We’ve then used the join() method to concatenate the strings together, adding a space character between each word.

Note that the join() method requires a sequence of strings as input, such as a list or a tuple. It returns a new string that contains all the elements of the sequence joined together with the specified separator. In this case, we’ve used a space character as the separator.