python 中字符串、元组、字典、列表之间的转换
dictionary
$ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> dict = {'name':'eric', 'age':18, 'job':'writer'} >>> #dict --- str ... print (type(str(dict))), str(dict) <class 'str'> (None, "{'age': 18, 'job': 'writer', 'name': 'eric'}") >>> #dict --- tuple ... print (tuple(dict)) ('age', 'job', 'name') >>> #dict --- list ... print (list(dict)) ['age', 'job', 'name'] >>>
list: 不能转换成dictionary
$ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> lis = ['hey', 'are' ,'you' ,'ok'] >>> #list --- str ... print (str(lis)) ['hey', 'are', 'you', 'ok'] >>> #list --- tuple ... print (tuple(lis)) ('hey', 'are', 'you', 'ok') >>>
string
$ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> str = '123qwe' >>> #str --- tuple ... print (tuple(str)) ('1', '2', '3', 'q', 'w', 'e') >>> #str --- list ... print (list(str)) ['1', '2', '3', 'q', 'w', 'e'] >>> #str 到dic转换 需要满足一定格式: >>> print (type(eval("{'name':'eric', 'age':18}"))),(eval("{'name':'eric', 'age':18}")) <class 'dict'> (None, {'name': 'eric', 'age': 18}) >>>
tuple
$ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> tup = (1, 2, 3, 'a', 's', 'd') >>> #tuple --- string just all the tuple's elements are string type >>> print (' '.join(tup)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected str instance, int found >>> tup = ('1', '2', '3', 'a', 's', 'd') >>> print (' '.join(tup)) 1 2 3 a s d >>> print (''.join(tup)) 123asd >>> #tuple --- list >>> tup = (1, 2, 3, 'a', 's', 'd') >>> print (list(tup)) [1, 2, 3, 'a', 's', 'd'] >>> #不可转换成字典
加密游戏
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ # Author: EricRay # Created Time : 2017-11-29 10:35:31 # File Name: censor.py # Description:将文本的特殊字符用'*' 代替 """ def censor(text, word): num = 0 text_y = '' text_t = text.split(' ') for i in range(len(text_t)): if text_t[i] == word: text_t[i] = '*' num += 1 if num == len(text_t): return '' else : return ' '.join(list(text_t)) text = (input('Please input text:')) word = (input('Please input word:')) print (censor(text, word)) #结果展示 $ python censor.py Please input text:you are so smart you you Please input word:you * are so smart * *
python 列表、字典、元组、字符串之间的转换
最新推荐文章于 2024-03-13 11:36:41 发布