3 - 各種變量與值之間的多種連接方式

字符串與字符串之間連接

# 字符串與字符串之間連接的方式有5 種
## 1:+(加號)
s1 = 'hello'
s2 = 'world'
s = s1 + s2
print(s)
helloworld
helloworld
用逗號連接: hello world

格式化: <hello> <world>
join連接: hello world
## 2: 直接連接
s = 'hello''world'
print(s)
helloworld
## 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)
用逗號連接: hello world
## 4: 格式化
s = '<%s> <%s>' % (s1, s2)
print('格式化:', s)
格式化: <hello> <world>
## 5: join
s = ' '.join([s1, s2])
print('join連接:', s)
join連接: hello world

字符串與非字符串之間連接

# 字符串與非字符串之間連接

s1 = 'hello'
s2 = 'world'

## 1:加號
n = 20
s = s1 + str(n)
print(s)
v = 12.44
b = True
print(s1 + str(n) + str(v) + str(b))
hello20
hello2012.44True
## 2: 格式化
s = '<%s> <%d> <%.2f>' % (s1, n, v)
print('格式化:', s)
格式化: <hello> <20> <12.44>
## 3: 重定向
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 - 進制之間的轉換

發佈了128 篇原創文章 · 獲贊 128 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章