What is String in Python and How to Concatenate Two String Variables

What is String in Python and How to Concatenate Two String Variables


In Python, a string is a sequence of characters. A string can be created by enclosing characters inside a single quote or double-quotes. For example:



Copy code

string1 = 'Hello World'

string2 = "Hello World"

To concatenate two string variables in Python, you can use the + operator. For example:


Copy code

string1 = 'Hello'

string2 = 'World'


string3 = string1 + string2

print(string3)  # Output: "HelloWorld"

You can also use the join() method to concatenate two string variables. The join() method is called on one string, and the other string is passed as a parameter to the join() method. The join() method inserts the second string in between the characters of the first string. For example:


Copy code

string1 = 'Hello'

string2 = 'World'


string3 = ''.join([string1, string2])

print(string3)  # Output: "HelloWorld"

You can also use the format() method to concatenate two string variables. The format() method takes the variables that you want to concatenate as arguments, and inserts them into the string at the specified positions. For example:


Copy code

string1 = 'Hello'

string2 = 'World'


string3 = '{} {}'.format(string1, string2)

print(string3)  # Output: "Hello World"

These are some of the ways in which you can concatenate two string variables in Python.

Comments