问题描述
我需要将列表转换为字符串,然后执行相反的过程.请注意,一个脚本将转换List-> String,而另一个脚本将转换String-> List,因此将列表存储在变量中不是解决方案.并非在所有情况下都使用split(',')或类似方法.因此,作为挑战,我邀请您在以下示例中进行转换:
I need to convert a list into a string and then do the reverse process. Note that one script will convert List->String and another script will convert String->List, so store the list in a variable is not a solution. Use split(', ') or similar is not a solution either in all cases. So, as a challange I invite you to do the conversion in the following example:
l = ['ab,.cd\'ac"', b'\x80', '\r\nHi, !', b'\x01']
str_l = str(l)
我尝试了一种可行的方法:使用exec()内置函数,但是人们说这不是一个好习惯,因此我邀请您给我另一种选择.我在函数内使用exec()时也遇到问题,但这是您可以检查的另一个问题->
I have tried one thing that worked: using exec() built-in function but people says is not a good practice, so I invite you to give me another alternative. Also I am having problems using exec() inside a function but that's another question that you can check -> Using exec() inside a function Python 3
推荐答案
这应该有效:
str_l = ("|").join(l)
哪个给您您的第一个字符串.然后做:
Which gives you your first string. Then do:
l_2 = str_l.split("|")
哪个会给您第二个列表.
Which gives you your second list.
这篇关于列出到字符串以列出Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!