立即學習:https://edu.csdn.net/course/play/26755/340111?utm_source=blogtoedu
不同的數據類型變量首尾相連
字符串與字符串之間
1. +
s1 = "hello"
s2 = "world"
s = s1 + s2
print(s)
2. 直接連接
s = "hello" "world"
print(s)
3. 輸出重定向
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print("hello", "world")
sys.stdout = old_stdout
print(result.getvalue())
4. 格式化輸出
s1 = "hello"
s2 = "world"
s = "%s %s" % (s1,s2)
print(s)
5. join
s1 = "hello"
s2 = "world"
s = " ".join([s1, s2])
print(s)
字符串和非字符串拼接
1. +
n = 20
v = 12.44
b = True
print(s + str(n) + str(v) + str(b))
2. 格式化
n = 20
v = 12.44
b = True
s = "%s %d %f %s" % (s1, n, v, b)
print(s)
3. 重定向
n = 20
v = 12.44
b = True
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print(n, v, b)
sys.stdout = old_stdout
print(result.getvalue())
字符串+class 輸出特定內容
實現class中的__str__方法
class MyClass:
def __str__(self):
return "myclass"
my = MyClass()
s = "test " + str(my)
print(s)