[英]How to remove brackets from python string?
我从标题中知道您可能认为这是重复的,但事实并非如此。
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 }})
这就是我的 Python 代码的样子。 大部分代码已被删除,但基本上我是从网站中提取一些信息。 我将信息保存为字典。 当我打印字典时,每个值都有一个括号 ["blbal"],这会导致我的 Iphone 应用程序出现问题。 我知道我可以将变量转换为字符串,但我想知道是否有办法将信息直接作为字符串获取。
看起来您在列表中有一个字符串:
["blbal"]
要获取字符串,只需 index l = ["blbal"]
print(l[0]) -> "blbal"
。
如果它是一个字符串,则使用str.strip
'["blbal"]'.strip("[]")
或 slicing '["blbal"]'[1:-1]
如果它们总是存在。
您也可以replace
为只用空字符串替换您不想要的文本/符号。
text = ["blbal","test"]
strippedText = str(text).replace('[','').replace(']','').replace('\'','').replace('\"','')
print(strippedText)
import re
text = "some (string) [another string] in brackets"
re.sub("\(.*?\)", "", text)
# some in brackets
# works for () and will work for [] if you replace () with [].
\(.*?\)
格式匹配括号,其中包含一些未指定长度的文本。 \[.*?\]
格式也匹配方括号,括号内有一些文本。
输出将不包含括号和其中的文本。
如果您只想匹配方括号,请将方括号替换为选择的括号,反之亦然。
要一次性匹配()
和[]
括号,请使用此格式(\(.*?\)|\[.*?\]:)
将两个模式与|
特点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.