字符串与字符串之间连接的方式有5种
1. 加号( + )
2. 直接连接(字符串类型的值,不能是变量)
s = "hello" "world"
print(s)
3. 逗号(,)连接
print('hello', 'world')
3. 输出重定位 (print函数)
from io import StringIO import sys old_stdout = sys.stdout result = StringIO() sys.stdout = result print('hello', 'world') # 恢复标准输出 sys.stdout = old_stdout result_str = result.getvalue() print(result_str) hello world
4. 格式化
5. join方法
s = " ".join([s1, s2])
字符串与非字符串之间如何连接
1:加号
s1 = 'hello' n = 20 v = 12.44 b = True print(s1 + str(n) + str(v) + str(b)) hello2012.44True
2:格式化
s = '%s%d%f' % (s1,n,v) print(s) s = '%s%d%.2f' % (s1,n,v) print(s) hello2012.440000 hello2012.44
3:重定向
s1 = 'hello' n = 20 v = 12.44 b = True from io import StringIO import sys old_stdout = sys.stdout result = StringIO() sys.stdout = result print(s1, n, v, b, sep='') # 恢复标准输出 sys.stdout = old_stdout result_str = result.getvalue() print(result_str) hello2012.44True
字符串与类
class MyClass: def __str__(self): return 'This is a MyClass Instance.' my = MyClass() s1 = 'hello' s = s1 + str(my) print(s) helloThis is a MyClass Instance.