如何从python字符串中删除括号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29459008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove brackets from python string?
提问by hamzah
I know from the title you might think that this is a duplicate but it's not.
我从标题中知道您可能认为这是重复的,但事实并非如此。
for id,row in enumerate(rows):
columns = row.findall("td")
teamName = columns[0].find("a").text, # Lag
playedGames = columns[1].text, # S
wins = columns[2].text,
draw = columns[3].text,
lost = columns[4].text,
dif = columns[6].text, # GM-IM
points = columns[7].text, # P - last column
dict[divisionName].update({id :{"teamName":teamName, "playedGames":playedGames, "wins":wins, "draw":draw, "lost":lost, "dif":dif, "points":points }})
This is how my Python code looks like. Most of the code is removed but essentially i am extracting some information from a website. And i am saving the information as a dictionary. When i print the dictionary every value has a bracket around them ["blbal"] which causes trouble in my Iphone application. I know that i can convert the variables to strings but i want to know if there is a way to get the information DIRECTLY as a string.
这就是我的 Python 代码的样子。大部分代码都被删除了,但本质上我是从网站中提取一些信息。我将信息保存为字典。当我打印字典时,每个值周围都有一个括号 ["blbal"],这会导致我的 Iphone 应用程序出现问题。我知道我可以将变量转换为字符串,但我想知道是否有办法将信息直接作为字符串获取。
采纳答案by Padraic Cunningham
That looks like you have a string inside a list:
看起来您在列表中有一个字符串:
["blbal"]
To get the string just index l = ["blbal"]
print(l[0]) -> "blbal"
.
要获取字符串只是 index l = ["blbal"]
print(l[0]) -> "blbal"
。
If it is a string use str.strip
'["blbal"]'.strip("[]")
or slicing '["blbal"]'[1:-1]
if they are always present.
如果它是一个字符串使用str.strip
'["blbal"]'.strip("[]")
或切片,'["blbal"]'[1:-1]
如果它们总是存在。