標籤:mat eee src 使用 產生 形式 過程 ogr 首碼
在學習Python(3x)的過程中,在拼接字串的時候遇到了些問題,所以抽點時間整理一下Python 拼接字串的幾種方式。
方式1,使用加號(+)串連,使用加號串連各個變數或者元素必須是字串類型(<class ‘str‘>)
例如:
str_name1 = ‘To‘str_name2 = ‘ny‘str_name = str_name1 + str_name2print(str_name)
輸出結果:
我是學C#出身的,把c#編程習慣用到了Python 上面,於是就出現了下面的代碼
number=34print(‘這個數是:‘+number)
編譯通過運行才發現行不通,出現了一下錯誤。
突然就懵了。
C#代碼
class Program { static void Main(string[] args) { //c# 字串使用"+"拼接 int num = 34; Console.WriteLine("這個數是:"+num); } }
編譯通過,執行結果如下
修改Python 代碼:
number=34
print(‘這個數是:‘+str(number))
方式三:使用.joiin(iterable) 拼接
print(‘-----------method3-----------‘)# method3 使用join拼接字串# str.join(iterable)# 可join的條件 join(iterable) iterable 可迭代的, 如果列表(list)為 非嵌套列表,列表元素為字串(str)類型,# 序列類型,散列類型 都可以作為參數傳入# eg(1):list_good_night = [‘晚‘, ‘上‘, ‘好‘, ‘!‘]str_night = ‘‘.join(list_good_night)print(str_night)# eg(2):# 拼接首碼 (‘拼接首碼‘).join(iterable)str_night1 = ‘------>‘.join(list_good_night)print(str_night1)# eg(3) 拼接 iterable = 字典 key,value 必須字串 預設拼接key 的列表dict_name = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}str_key = ‘,‘.join(dict_name)# 拼接value 的列表str_value = ‘,‘.join(dict_name.values())print(str_key)print(str_value)
執行結果:
方式四:使用逗號(,)拼接
# method4 使用逗號(,)串連# 使用,逗號形式要注意一點,就是只能用於print列印,賦值操作會產生元組:print(‘-----------method4-----------‘)a, b = ‘Hello‘, ‘word‘c = a, bprint(a, b)print(c)print(type(c))
輸出結果:
方式五:直接拼接
# mehon5 直接連接print(‘-----------method5-----------‘)print(‘hello‘‘python‘)
方式六:format 拼接
# mehon5 直接連接print(‘-----------method5-----------‘)print(‘hello‘‘python‘)# methon6 format 拼接 str.format(args,**kwargs)# eg(1) {} 充當預留位置str_word = ‘hello, word! {} {}‘.format(‘張三‘, ‘李四‘)print(str_word)# eg(2) {[index]} 按索引位置填充 .format([0]=value1, [1]= value1},)str_word_index0 = ‘hell0, word!{0},{1}‘.format(‘張三‘, ‘李四‘)str_word_index1 = ‘hell0, word!{1},{0}‘.format(‘張三‘, ‘李四‘)print(str_word_index0)print(str_word_index1)# eg(3) {[keyword]}str_word_keyword = ‘hell0, word!{a},{b}‘.format(b=‘張三‘, a=‘李四‘)print(str_word_keyword)# eg(4) {[keyword,indec]} keyword 放在最後str_word1 = ‘hell0, word!{1}{a}{0},{b}‘.format(‘index0‘, ‘index1‘, b=‘張三‘, a=‘李四‘)print(str_word1)# eg(5) format 參數類型不限,當為元祖,列表,集合,字典時輸出str_word2 = ‘hell0, word!{b}‘.format(b=[‘eee‘, ‘d‘])print(str_word2)# eg(6) 作為函數使用str_word3 = ‘hello, word! {} {}‘.formatword = str_word3(‘張三‘, ‘李四‘)print(word)
輸出結果:
Python 拼接字串的幾種方式