Thanks to visit codestin.com
Credit goes to www.w3schools.in

Concatenate Strings in Python

Python Programming Examples

Python String Programs

In Python, string concatenation refers to the process of combining two or more strings into a single string. There are various ways to concatenate strings in Python, which are explained in this tutorial.

Concatenate Strings Using + Operator

To concatenate (combine) two strings in Python, the + operator can be used.

Example Program:

string1 = "W3schools"
string2 = ".in"

result = string1 + string2
print(result)

The above example will print "W3schools.in".

Concatenate Strings Using join() Method

In Python, the join() method is a string method that concatenates (combines) a list of strings into a single string. This method takes a list of strings as an argument and returns a single string which is the concatenation of all the strings in the list.

Example Program:

strings = ["Hello", "Python", "Test"]
result = "".join(strings)
print(result)

The above program will print "HelloPythonTest".

A separator string can also be used with the join() method to insert a separator between the strings. For example:

Example Program:

strings = ["Hello", "Python", "Test"]
result = " ".join(strings)
print(result)

The above program will print the "Hello Python Test" because the separator is a space character.

Concatenate Strings Using F-String

The f-strings feature introduced in Python 3.6 can be used to concatenate strings. An f-string is a string literal prefixed with the letter f and allows you to embed expressions inside a string. For example:

Example Program:

string1 = "Hello"
string2 = "Python"

result = f"{string1} {string2}"
print(result)

The above program will also print "Hello Python".



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram