Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将字符串转换为列表_Python 3.x_List_Python 2.7 - Fatal编程技术网

Python 3.x 将字符串转换为列表

Python 3.x 将字符串转换为列表,python-3.x,list,python-2.7,Python 3.x,List,Python 2.7,我试图读取文件中的条目并将其转换为列表 with open('myfile1.txt') as f: lines = [line.rstrip() for line in f] print(lines) ###['10.0.0.1', '10.0.0.2'] print(type(lines)) ###<type 'list'> catch = (json.dumps(lines)) ###For replacing sin

我试图读取文件中的条目并将其转换为列表

with open('myfile1.txt') as f:
    lines = [line.rstrip() for line in f]

print(lines)            ###['10.0.0.1', '10.0.0.2']
print(type(lines))      ###<type 'list'>

catch = (json.dumps(lines))         ###For replacing single quotes to double
print(catch)                        ###["10.0.0.1", "10.0.0.2"]
print(type(catch))                  ###<type 'str'>

catch_1 = list(catch.split("''"))    ###Converting str to list
print(catch_1)                       ###['["10.0.0.1", "10.0.0.2"]']
以open('myfile1.txt')作为f的
:
lines=[line.rstrip()表示f中的行]
打印(行)###['10.0.0.1','10.0.0.2']
打印(打印(行))###
catch=(json.dumps(line))####用于将单引号替换为双引号
打印(捕获)###[“10.0.0.1”、“10.0.0.2”]
打印(类型(捕捉))###
catch_1=list(catch.split(“'')####将str转换为list
打印(catch_1)###['[“10.0.0.1”,“10.0.0.2”]']
有没有更好的方法可以在不更改类型的情况下将引号从单引号替换为双引号

File entries :
10.0.0.1
10.0.0.2

Expected Output :
["10.0.0.1", "10.0.0.2"]
 <type 'list'>
文件条目:
10.0.0.1
10.0.0.2
预期产出:
["10.0.0.1", "10.0.0.2"]

请让我知道,谢谢。

'
包围的字符串完全相同。
[“10.0.0.1”、“10.0.0.2”]
[“10.0.0.1”、“10.0.0.2”之间没有区别
内部。打印列表时,这只是一个区别。如果您想在打印列表时使用双引号,可以执行以下操作:

a = ['10.0.0.1', '10.0.0.2']
print(str(a).replace("'", '"'))
这将打印
[“10.0.0.1”、“10.0.0.2”]


回答您的问题“是否有更好的方法在不更改类型的情况下将引号从单引号替换为双引号?”?“。您的程序中不存在引号!列表和字符串没有引号的概念。它们仅在打印列表或将列表转换为字符串时添加。

是否尝试将
['10.0.0.1','10.0.0.2']
中的单引号替换为
['10.0.0.1','10.0.0.2']
?@RoadRunner是的。但它们是一样的?是的,但我的代码中有一个要求,它只将输入作为双引号。