立即学习:https://edu.youkuaiyun.com/course/play/26755/340111?utm_source=blogtoedu
问题:
1、字符串与字符串之间连接有几种方式
2、字符串如何与非字符串之间连接
3、字符串与对象连接时如何让对象输出特定的内容,如MyClass
第一题:
#字符串与字符串之间的连接方式(至少五种)
####1:+(加号)
s1 = 'hello'
s2 = 'world'
print("加号连接:",s1 + s2)
####2:直接连接
s = "hello""world"
print("直接连接:",s)
####3:用逗号(,)连接,标准输出的重定向
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)
####4:格式化
s = '<%s> <%s>' % (s1,s2) #后面是元组
print('格式化:',s)
####5:join
s = ' '.join([s1,s2])
print('join:',s)
输出如下:
第二题:
#字符串与非字符串之间的连接
###1:加号
n = 20
s = 'hello'
v = 12.44
b = True
print("加号连接:",s + str(n) + str(v) + str(b))
###2:格式化
s = '<%s> <%d> <%.2f>' %(s,n,v)
print('格式化:',s)
###3:重定向
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print(s, True,n,v,sep='*')
sys.stdout = old_stdout #恢复标准输出
result_str = result.getvalue()
print("用逗号连接:",result_str)
输出如下:
第三题:
class MyClass:
def __str__(self):
return 'This is a MyClass Instance. '
my = MyClass()
s = 'hello' + str(my)
print(s)
输出如下: