[英]Remove substring of digits from string (Python)
<elem1><elem2>20,000 Leagues Under the Sea1050251</elem2></elem1>
<elem1><elem2>1002321Robinson Crusoe1050251</elem2></elem1>
我正在使用 XML 文件,并且必须将从上面提取的元素插入到另一个 XML 文件中。 问题是,我不知道如何从字符串中删除用于跟踪 position 的 id(7 位子字符串)。 删除“>”和“<”之间的字符是不可行的,因为文本有时以 id 开头,有时以数字开头的标题。 我需要的是只能从字符串中删除任何 7 位子字符串的东西,但我只找到了可以对指定子字符串执行此操作的代码
您可以尝试使用正则表达式:
import re
string = """<elem1><elem2>20,000 Leagues Under the Sea1050251</elem2></elem1>
<elem1><elem2>1002321Robinson Crusoe1050251</elem2></elem1>"""
pattern = re.compile(r"\d{7}") # pattern that matches exactly 7 consecutive ascii digits
result = pattern.sub("", string) # returns a string where the matched pattern is replaced by the given string
print(result)
Output:
<elem1><elem2>20,000 Leagues Under the Sea</elem2></elem1>
<elem1><elem2>Robinson Crusoe</elem2></elem1>
有用:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.