立即学习:https://edu.csdn.net/course/play/26755/340111?utm_source=blogtoedu
字符串与字符串之间的连接:
1. 加号(+)
s1 = 'hello'
s2 = 'world'
print(s1+s2)
2. 直接连接
s = 'hello''world'; print(s)
3. 标准输出重定向
# 逗号(,)连接
print('hello','world')
# 如需将打印结果保存到变量中可以使用:标准化输出重定向
from io import StringIO
import sys
old_stdout = sys.stdout # 保存标准输出
result = StringIO() # 标准输入定位到字符串中
sys.stdout = result
print("hello", "world") # 可以使用参数:sep设置连接的字符如:*、# 等
sys.stdout = old_stdout # 恢复标准输出
result_str = result.getvalue()
print("用逗号连接:", result_str)
4. 格式化
# 格式化方式很多
s1 = 'hello'
s2 = 'world'
s = '<%s> <%s>' %(s1,s2)
5. .join()
s1 = 'hello'
s2 = 'world'
print(" ".join([s1,s2])); print("".join((s1,s2)))
字符串与非字符串之间的连接:
1. 加号(+)
非字符串需进行类型转换 str()
2. 标准输出重定向
3. 格式化