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']

  

按分隔符互相转换

1. 字符串转列表

str1 = "hi hello world"
print(str1.split(" "))
输出:
['hi', 'hello', 'world']

 

2. 列表转字符串

l = ["hi","hello","world"]
print(" ".join(l))
输出:
hi hello world

 

3 format

    def __str__(self):
        return '{0}({1})'.format(self.code,self.email)
#{}内部替换为format里的数据。有多个可以按数字顺序添加

  

posted @ 2018-09-26 17:50  jabbok  阅读(733)  评论(0编辑  收藏  举报