join two strings in python

In Python, there are different ways to join two or more strings together. One of the most common methods is to use the + operator or concatenation.

main.py
# Using concatenation with the + operator
string1 = "Hello"
string2 = "world"
result = string1 + " " + string2
print(result) # Output: "Hello world"
149 chars
6 lines

Another way to merge two strings is to use the join() function. The join() function is a string method that concatenates all the elements in an iterable (e.g., list, tuple) separated by a delimiter to form a new string.

main.py
# Using join() method
words = ["Hello", "world"]
delimiter = " "
result = delimiter.join(words)
print(result) # Output: "Hello world"
134 chars
6 lines

In the example above, the join() method first creates a string with all the elements in the words list separated by a space, resulting in the string "Hello world".

gistlibby LogSnag