'''
字符串与字符串之间如何连接,有几种方式
'''
#第1种 使用 + (加号)
s1 = 'hello'
s2 = 'world'
s = s1 + s2
print(s+'\n')
#第2种 直接连接
s = 'hello' 'world''\n'
print(s)
#第3种 使用逗号(,)连接,标准输出的重定向
print('hello','world','\n')
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print('hello','world')
sys.stdout = old_stdout
print('用逗号连接:',result.getvalue())
#第4种 格式化 %
s = '<%s> <%s>\n'%(s1,s2)
print(s)
#第5种 join
s = ' '.join([s1,s2])
print('join连接:',s,'\n\n\n')
'''
字符串与非字符串之间如何连接
'''
#1:加号+
n = 20
b = True
print(s1 + str(n) + str(b) + '\n')
#2:格式化%
s = '<%s> <%d> <%.2f>\n'%(s1,n,1.235)
print(s)
#3:重定向
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print(s1,n,b,sep='**')
sys.stdout = old_stdout
print('重定向:',result.getvalue(),'\n\n')
'''
字符串与对象连接如何让对象输出特定内容
'''
class MyClass():
def __str__(self):
return ' This is a MyClass instance'
my = MyClass()
print(s1 + str(my))
The result:
helloworld
helloworld
hello world
用逗号连接: hello world
join连接: hello world
hello20True
<20> <1.24>
重定向: hello20True
hello This is a MyClass instance