How to concatenate strings and data in Python

Published on Aug. 22, 2023, 12:15 p.m.

To concatenate strings and data in Python, you can use the string formatting syntax, which allows you to substitute values into a string. Here is an example:

name = "Alice"
age = 25
message = "My name is {} and I am {} years old".format(name, age)
print(message)

Output: My name is Alice and I am 25 years old

In this example, the placeholders in the string are replaced with the values of the name and age variables using the format method.

Alternatively, you can use f-strings (formatted string literals) introduced in Python 3.6. Here is an example:

name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old"
print(message)

Output: My name is Alice and I am 25 years old

In this example, the f before the opening quote indicates that the string should be formatted, and the values of the name and age variables are inserted into the string using curly braces .

Tags:

related content