如何删除[' ']来自字符串变量

时间:2017-11-21 18:39:40

标签: python

打开保存的文本文件1 =是0 =否。所以我想让python读取第1行并设置一个变量。该变量以

出现
  

[' 1 \ n']

我只想要" 1"所以我设法用代码行删除了\ n

played=[i.replace("\n", "") for i in played ]
played=[i.replace("['", "") for i in played ]
played=[i.replace("']", "") for i in played ]

但我还是出来了

  

[' 1']

有没有人知道删除方括号和单个语音标记的方法 感谢

2 个答案:

答案 0 :(得分:1)

这是因为它实际上是一个列表。你可以用这个来解决这个问题:

played=int(played[0])

答案 1 :(得分:0)

只需将其转换为带有int强制转换的整数,然后访问第一项:

played=[int(i.replace("\n", "")) for i in played ][0]
>>> played = ["1\n"]
>>> played=[int(i.replace("\n", "")) for i in played ][0]
>>> played
1
>>>