- Python日常
内容展示: ①:字符串与字符串连接:
1.加号(+)
s1 = 'Hello' s2 = 'World' s = s1 + s2 print(s) # Hello World
2.直接连接
s = 'Hello World print(s) # Hello World
3.逗号相连, 标准输出的重定向
from io import StringIO
import sys
old_stdout = sys.stdout # 方便后续恢复标准输出
result = StringIO()
sys.stdout = result
print('Hello', 'World')
sys.stdout = old_stdout # 恢复标准输出
reslut_str = result.getvalue()
print('用逗号连接: ', reslut_str) # 用逗号连接: Hello World
4.格式化
s1 = 'Hello'
s2 = 'World'
s = '<%s> <%s>' % (s1, s2)
print('格式化: ', s)
5.使用join
s = ''.join([s1, s2])
print('join连接:', s)
②:字符串与非字符串连接:
1.加号(+)
n = 20 s1 = 'Hello' s = s1 + str(n) # 使用str进行类型转换 print(s) # Hello20
2.格式化
s1 = 'Hello' n = 20 f = 24.24 s = '<%s> <%d> <%.2f>' %(s1, n, f) # .2f 小数点后保留两位 print(s) #<20> <24.24>
3.重定向
from io import StringIO
import sys
s1 = 'Hello'
n = 20
f = 24.24
b = True
old_stdout = sys.stdout # 方便后续恢复标准输出
result = StringIO()
sys.stdout = result
print(s1, b, n, f, sep='*') # sep定义输出间隔
sys.stdout = old_stdout # 恢复标准输出
reslut_str = result.getvalue()
print('用逗号连接: ', reslut_str) # 用逗号连接: Hello*True*20*24.24
sep定义输出间隔
③字符串与对象连接时让对象输出特定内容
s1 = 'Hello '
class MyClass:
def __str__(self):
return 'I am Strong' # return 为我们想要输出的内容
my = MyClass()
s = s1 + str(my) # 使用str进行类型转换
print(s) # Hello I am Strong
总结:
1.在字符串与非字符串或者对象连接时,注意类型的转换(str)
2.使用格式化连接的时,注意<%?> 要与后方数据类型对应
- CSDN Python日常 第3 篇
- 下一篇链接



