python字符串/列表/字典互相轉換


python字符串/列表/字典互相轉換

目錄

字符串與列表

字符串與字典

列表與字典

 字符串與數值

字符串與列表

字符串轉列表

1.整體轉換

str1 = 'hello world'
print(str1.split('這里傳任何字符串中沒有的分割單位都可以,但是不能為空'))
# 輸出:['helloworld']

2.分割

str2 = "hello world"
list2 = list(str2)
print(list2)
#輸出:['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

 

str3 = "en oo nn"
list3 = str3.split()
# list2 = str3.split(" ")
print(list3)
#輸出:['en', 'oo', 'nn']

 

列表轉字符串

1.拼接

list1 = ['hello','world']
res = list1[0] + list1[1]
print(res)
# 輸出:helloworld

2.join

list2 = ['hello','world']
# 引號中的內容為,連接各個字符串的字符
print("".join(list2))
print(" ".join(list2))
print(".".join(list2))
# 輸出:helloworld
# 輸出:hello world
# 輸出:hello.world

 

 

字符串與字典

字符串轉字典

請查看這篇博文

 

字典轉字符串

1.json

import json
dict_1 = {'name':'linux','age':18}
dict_string = json.dumps(dict_1)
print(type(dict_string))
#輸出:<class 'str'>

2.強制

dict_2 = {'name':'linux','age':18}
dict_string = str(dict_2)
print(type(dict_string))
#輸出:<class 'str'>

 

列表與字典

列表轉字典

兩個列表

list1 = ['k1','k2','k3'] 、 list2 = [1,2,3] ,轉換成字典{’k1‘:1,'k2':2,'k3':3}

list1 = ['k1','k2','k3']
list2 = [1,2,3]
print(dict(zip(list1,list2)))
#輸出:{'k1': 1, 'k2': 2, 'k3': 3}

#zip() 函數用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表。 zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中為了減少內存,zip() 返回的是一個對象。如需展示列表,需手動 list() 轉換;如需展示成字典,需要手動dict()轉換,如果元素個數不對應會報錯。

嵌套列表

list2 = [['key1','value1'],['key2','value2'],['key3','value3']]
print(dict(list2))
#輸出:{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

字典轉列表

dict = {'name': 'Zara', 'age': 7, 'class': 'First'}
print(list(dict))
#輸出:['name', 'age', 'class']

 

 字符串與數值

字符串轉數值

int(str) 函數將 符合整數的規范的字符串 轉換成 int 型。

num2 = "123";
num2 = int(num1);
print("num2: %d" % num2);

float(str) 函數將 符合 浮點型 的規范的字符串 轉換成 float 型。

num1 = "123.12";
num2 = float(num1);
print("num2: %f" % num2);

數值轉字符串

str(num) 將 整數,浮點型轉換成 字符串。

num = 123;
mystr = str(num);
print ("%s" % mystr);

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM