python 多行字符串如何拼接变量

在 Python 中,将变量拼接到多行字符串中有多种方法,以下是常见的几种方式:


1. ‌使用 f-string(Python 3.6+ 推荐)‌

用 f"" 或 F"" 前缀定义多行字符串,变量直接通过 {变量名} 嵌入。

pythonCopy Code
 
name = "Alice" age = 30 msg = f""" Hello {name}, Your age is {age}. """ print(msg)

‌输出:‌

textCopy Code
 
Hello Alice, Your age is 30.

‌注意‌:字符串中的缩进会被保留(例如换行后的行首空格),需根据实际需求调整格式。


2. ‌使用 format() 方法‌

通过 {} 占位符,再调用 .format() 传入变量。

pythonCopy Code
 
name = "Bob" age = 25 msg = """ Hello {name}, Your age is {age}. """.format(name=name, age=age) print(msg)

‌输出:‌

textCopy Code
 
Hello Bob, Your age is 25.

3. ‌旧式 % 格式化‌

使用 % 操作符配合类型占位符(如 %s%d)。

pythonCopy Code
 
name = "Charlie" age = 28 msg = """ Hello %s, Your age is %d. """ % (name, age) print(msg)

‌输出:‌

textCopy Code
 
Hello Charlie, Your age is 28.

4. ‌多行字符串拼接(灵活换行)‌

通过括号 () 或反斜杠 \ 拼接多行字符串,灵活插入变量。

pythonCopy Code
 
user = "Dave" score = 95 msg = ( f"User: {user}\n" f"Score: {score}/100" ) print(msg)

‌输出:‌

textCopy Code
 
User: Dave Score: 95/100
posted @ 2025-03-24 22:31  eagle88  阅读(195)  评论(0)    收藏  举报