日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python實現將list拼接為一個字符串_python

作者:測試開發小白變怪獸 ? 更新時間: 2022-12-22 編程語言

將list拼接為一個字符串

在 python 中如果想將 list 拼接為一個字符串,可使用 join() 方法。

join() 方法描述

將序列(列表或元組)中的元素以指定的字符連接成一個新的字符串。

語法

str.join(sequence)

  • str:指定的字符
  • sequence:待連接的元素序列

返回值為通過指定字符連接序列中的元素后生成的新字符串。

舉例

>>> str = ' '
>>> seq = ['I','am','superYujx']
>>> print(str.join(seq))

I am superYujx ? ?# 輸出結果

>>> str = '_'
>>> seq = ('I','am','superYujx')
>>> print(str.join(seq))

I_am_superYujx ? ?# 輸出結果

Python兩個list一對一拼接

'''
實現兩個list元素1對1拼接
實現結果:1-8-314,99-2-6332
'''
def main():
    list1 = ['0108', '9902', '207']
    list2 = ['314', '6332', '0305']
    list4 = []
    for i in range(0, len(list1)):  #len(list1)獲取列表長度
        list1_len1 = len(list1[i])  #元素長度
        if list1_len1 == 4:
            l1_build = list1[i][:2].lstrip("0")  #去除前面的0
            l1_unit = list1[i][3]
        else:
            l1_build = list1[i][:1]
            l1_unit = list1[i][2]
        l2_room = list2[i]
        # list3 = [l1_build + '-' + l1_unit + '-' + l2_room]
        # list4.append(list3[0])
        list3 = l1_build + '-' + l1_unit + '-' + l2_room
        print("list3:", list3, end=",")
        list4.append(list3)
    print('\n')
    print("list4:", list4)
 
 
 
if __name__=="__main__":
    main()

運行結果:

list3: 1-8-314,list3: 99-2-6332,list3: 2-7-0305,
?
list4: ['1-8-314', '99-2-6332', '2-7-0305']

原文鏈接:https://blog.csdn.net/yu97271486/article/details/105996934

欄目分類
最近更新