字符串與字符串之間連接
s1 = 'hello'
s2 = 'world'
s = s1 + s2
print(s)
helloworld
helloworld
用逗號連接: hello world
格式化: <hello> <world>
join連接: hello world
s = 'hello''world'
print(s)
helloworld
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
s = '<%s> <%s>' % (s1, s2)
print('格式化:', s)
格式化: <hello> <world>
s = ' '.join([s1, s2])
print('join連接:', s)
join連接: hello world
字符串與非字符串之間連接
s1 = 'hello'
s2 = 'world'
n = 20
s = s1 + str(n)
print(s)
v = 12.44
b = True
print(s1 + str(n) + str(v) + str(b))
hello20
hello2012.44True
s = '<%s> <%d> <%.2f>' % (s1, n, v)
print('格式化:', s)
格式化: <hello> <20> <12.44>
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print(s1, True, n, v, sep='*')
sys.stdout = old_stdout
result_str = result.getvalue()
print('用逗號連接:', result_str)
用逗號連接: hello*True*20*12.44
輸出對象特定數據
s1 = 'hello'
class MyClass:
def __str__(self):
return 'This is a MyClass Instance.'
my = MyClass()
s = s1 + str(my)
print(s)
helloThis is a MyClass Instance.
4 - 進制之間的轉換