Python字符串拼接主要有五种方法:1. +运算符适合简单拼接但性能差;2. f-string语法简洁高效,推荐现代Python使用;3. str.join()适用于列表拼接,性能最优;4. str.format()功能灵活,可读性好;5. %操作符较老,逐渐被替代。

Python里字符串拼接这事儿,说起来方法还真不少,核心上无非就是用
+
str.join()
%
str.format()
要说Python里字符串怎么拼接,我们手头可选择的工具箱里有几把趁手的:
1. +
name = "Alice" greeting = "Hello, " + name + "!" print(greeting) # 输出: Hello, Alice!
但话说回来,这玩意儿在拼接少量字符串时确实没毛病,可一旦字符串数量多了,或者在一个循环里反复拼接,那性能可就有点吃不消了。每次
+
2. f-string (格式化字符串字面量):现代Python的宠儿 从Python 3.6开始,f-string简直是神器。它把表达式直接嵌入到字符串字面量里,代码写起来干净利落,读起来也一目了然。而且,它的性能也相当不错,比
str.format()
%
name = "Bob"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message) # 输出: My name is Bob and I am 30 years old.
# 甚至可以内嵌表达式
price = 19.99
quantity = 3
total = f"The total is ${price * quantity:.2f}."
print(total) # 输出: The total is $59.97.这简直是为可读性和效率而生。
立即学习“Python免费学习笔记(深入)”;
3. str.join()
str.join()
+
words = ["Python", "is", "awesome"] sentence = " ".join(words) print(sentence) # 输出: Python is awesome data = ["user_id:123", "status:active", "timestamp:2023-10-27"] log_entry = "; ".join(data) print(log_entry) # 输出: user_id:123; status:active; timestamp:2023-10-27
join()
+
4. str.format()
%
str.format()
%
name = "Charlie"
job = "developer"
info = "{} is a {}.".format(name, job)
print(info) # 输出: Charlie is a developer.
# 可以通过索引或关键字参数指定位置
info_indexed = "{0} is a {1} and {0} loves coding.".format(name, job)
print(info_indexed) # 输出: Charlie is a developer and Charlie loves coding.
info_keyword = "{n} is a {j}.".format(n=name, j=job)
print(info_keyword) # 输出: Charlie is a developer.虽然f-string现在更受青睐,但
format()
以上就是python中字符串怎么拼接_Python字符串拼接常用方法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号