深度阅读

How to concatenate strings and data in Python

作者
作者
2023年08月22日
更新时间
9.33 分钟
阅读时间
0
阅读量

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 .

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。