Python3中內置類型bytes和str用法及byte和string之間各種編碼轉換,python--列表,元組,字符串互相轉換


Python3中內置類型bytes和str用法及byte和string之間各種編碼轉換

 

python--列表,元組,字符串互相轉換

列表,元組和字符串python中有三個內建函數:,他們之間的互相轉換使用三個函數,str(),tuple()和list(),具體示例如下所示

>>> s = "xxxxx"
>>> list(s)
['x', 'x', 'x', 'x', 'x']
>>> tuple(s)
('x', 'x', 'x', 'x', 'x')
>>> tuple(list(s))
('x', 'x', 'x', 'x', 'x')
>>> list(tuple(s))
['x', 'x', 'x', 'x', 'x']

  列表和元組轉換為字符串則必須依靠join函數

>>> "".join(tuple(s))
'xxxxx'
>>> "".join(list(s))
'xxxxx'
>>> str(tuple(s))
"('x', 'x', 'x', 'x', 'x')"
>>>

 

python字符串/元組/列表/字典互轉

#-*-coding:utf-8-*- 

#1、字典
dict = {'name': 'Zara', 'age': 7, 'class': 'First'}

#字典轉為字符串,返回:<type 'str'> {'age': 7, 'name': 'Zara', 'class': 'First'}
print type(str(dict)), str(dict)

#字典可以轉為元組,返回:('age', 'name', 'class')
print tuple(dict)
#字典可以轉為元組,返回:(7, 'Zara', 'First')
print tuple(dict.values())

#字典轉為列表,返回:['age', 'name', 'class']
print list(dict)
#字典轉為列表
print dict.values

#2、元組
tup=(1, 2, 3, 4, 5)

#元組轉為字符串,返回:(1, 2, 3, 4, 5)
print tup.__str__()

#元組轉為列表,返回:[1, 2, 3, 4, 5]
print list(tup)

#元組不可以轉為字典

#3、列表
nums=[1, 3, 5, 7, 8, 13, 20];

#列表轉為字符串,返回:[1, 3, 5, 7, 8, 13, 20]
print str(nums)

#列表轉為元組,返回:(1, 3, 5, 7, 8, 13, 20)
print tuple(nums)

#列表不可以轉為字典

#4、字符串

#字符串轉為元組,返回:(1, 2, 3)
print tuple(eval("(1,2,3)"))
#字符串轉為列表,返回:[1, 2, 3]
print list(eval("(1,2,3)"))
#字符串轉為字典,返回:<type 'dict'>
print type(eval("{'name':'ljq', 'age':24}"))

  


免責聲明!

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



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