Here are the 5 ways to concatenate strings in Python:
Method 1: Using + operator
The most straightforward way to concatenate strings is by using the + operator.
Visual Representation
Example
string1 = "Krunal"
string2 = "Lathiya"
combined_string = string1 + " " + string2
print(combined_string)
Output
Krunal Lathiya
Method 2: Using join() method
The join() method joins the elements of an iterable (like a list or tuple) into a single string.
Example
list1 = ["Krunal", "Lathiya"]
name = " ".join(list1)
print(name)
Output
Krunal Lathiya
Method 3: Using % Operator
The % operator is an older method for string formatting and can be used for concatenation.
Example
string1 = "Lathiya"
string2 = "Krunal %s" % string1
print(string2)
Output
Krunal Lathiya
Method 4: Using format() function
The str.format() method allows for multiple substitutions and value formatting.
It allows the concatenation of elements within a string through positional and named formatting.
Example
string1 = "Krunal"
string2 = "Lathiya"
name = "{} {}".format(string1, string2)
print(name)
Output
Krunal Lathiya
Method 5: Using f-string
If you are using Python 3.6 or later, you can use f-strings, which provide a way to embed expressions inside string literals and can also be used for concatenation.
Example
string1 = "Krunal"
string2 = "Lathiya"
name = f'{string1} {string2}'
print('Using f-string:', name)
Output
Using f-string: Krunal Lathiya