[英]Python get N characters from string with specific substring
我从图像文件中提取了一个很长的字符串。 字符串看起来像这样
...\n\nDate: 01.01.2022\n\nArticle-no: 123456789\n\nArticle description: asdfqwer 1234...\n...
如何仅提取 substring "Article-no:"
之后的 10 个字符?
我尝试使用像这样的 rfind 使用不同的方法来解决它,但是如果开始和结束字符串不准确,它往往会时不时地失败。
s = "... string shown above ..."
start = "Article-no: "
end = "Article description: "
print(s[s.find(start)+len(start):s.rfind(end)])
您可以使用split
:
string.split("Article-no: ", 1)[1][0:10]
为此,正则表达式可能会派上用场。
import re
# Create a pattern which matches "Article-no: " literally,
# and then grabs the digits that follow.
pattern = re.compile(r"Article-no: (\d+)")
s = "...\n\nDate: 01.01.2022\n\nArticle-no: 123456789\n\nArticle description: asdfqwer 1234...\n..."
match = pattern.search(s)
if match:
print(match.group(1))
这输出:
123456789
使用的正则表达式是Article-no: (\d+)
,它有以下部分:
Article-no: # Match this text literally
( # Open a new group (i.e. group 1)
\d+ # Match 1 or more occurrences of a digit
) # Close group 1
re
模块将在字符串中搜索匹配的位置,然后您可以从匹配中提取数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.