how to format join string in python

In Python, you can use string formatting to join multiple strings together. Here's an example:

main.py
name = "Alice"
age = 30
output = "My name is {} and I'm {} years old.".format(name, age)
print(output) # Output: "My name is Alice and I'm 30 years old."
154 chars
5 lines

In the above example, we define two variables name and age, and use the str.format() method to join them together with a string. Within the string, we use placeholders {} to indicate where we want to include the variable values. The order of arguments passed to str.format() corresponds to the order of the placeholders in the string.

Alternatively, you can use f-strings (formatted string literals) in Python 3.6 and above:

main.py
name = "Alice"
age = 30
output = f"My name is {name} and I'm {age} years old."
print(output) # Output: "My name is Alice and I'm 30 years old."
144 chars
5 lines

With f-strings, you can directly include variable values within a string by prefixing the string with f and enclosing the variable names in braces. The variable names are evaluated as expressions within the string.

related categories

gistlibby LogSnag