
PYTHON — String Concatenation Exercise in Python
Without requirements or design, programming is the art of adding bugs to an empty text file. — Louis Srygley
String concatenation is a fundamental operation in Python that involves combining two or more strings into a single string. In this tutorial, you’ll learn how to concatenate strings and add a space between them using Python.
To get started, you can use the following code snippet to concatenate two strings and print the resulting string:
# Concatenate two strings
string1 = "Hello"
string2 = "World"
result = string1 + string2
print(result)In this example, “Hello” and “World” are concatenated to form the string “HelloWorld”. If you want to add a space between the two words, you can simply include the space within the concatenation:
# Concatenate two strings with a space
result_with_space = string1 + " " + string2
print(result_with_space)The output of the second print statement will be “Hello World”, with a space between the two words.
You can also use the += operator for concatenation, which is a shorthand for concatenating and assigning the result back to the original variable:
# Using the += operator for concatenation
string3 = "Python"
string3 += " is"
string3 += " awesome"
print(string3)The output of the third print statement will be “Python is awesome”.
In Python, you can also concatenate strings with variables and convert non-string data types to strings using the str() function. For example:
# Concatenating strings with variables
name = "Alice"
age = 25
greeting = "Hello, my name is " + name + " and I am " + str(age) + " years old."
print(greeting)The output of the final print statement will be “Hello, my name is Alice and I am 25 years old.”
In summary, string concatenation is a common operation in Python for combining strings. You can use the + operator, += operator, and the str() function to concatenate strings, add spaces, and include variables in the concatenated result.





