带尾随字符的子串问题

2024-10-01 02:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用一个子字符串函数从一个较长的字符串(duh)中获取我需要的特定子字符串

假设我的字符串是:“(..)partijen waarvan de下四分位0,68%bedraagt en de上四分位2,06%

我追求的是大胆的价值观。现在,以下两个功能可以完美地工作:

content_higher = content_conclusion[content_conclusion.index("upper quartile"):content_conclusion.index("%.")]
content_lower = content_conclusion[content_conclusion.index("lower quartile"):content_conclusion.index("%")]

如您所见,对于“上四分位”(这是Transfer pricing/tax related),%字符后面跟着一个点(.),因为字符串在这里结束

当我将函数更改为查找上四分位值为下四分位值时,该函数不再工作:

content_higher = content_conclusion[content_conclusion.index("upper quartile"):content_conclusion.index("%")] #i.e., without the dot (.) that follows the % character

我理解这可能是因为这个%符号总是直接(即没有空格)后跟一个点(.)。但是,是否可以忽略以下字符。 我希望能够搜索特定的字符/子字符串,而不管该子字符串后面紧接着什么

换句话说,我可以使用通配符在特定字符上生成子字符串

希望以上是清楚的。非常感谢您的投入


Tags: the函数字符串indexdecontent字符upper
2条回答

可以使用Python正则表达式来实现这一点

参考:https://docs.python.org/3/howto/regex.html

我想出了下面的解决办法

import re

txt = "partijen waarvan de lower quartile 0,68% bedraagt en de upper quartile 2,06%."
x = re.findall("lower quartile \d,\d\d%", txt)
y = re.findall("upper quartile \d,\d\d%", txt)

print(f'Lower Quartile: {x[0][-5:]}')
print(f'Upper Quartile: {y[0][-5:]}')

### Output
# Lower Quartile: 0,68%
# Upper Quartile: 2,06%

一种选择是在匹配数字后使用以单词边界结尾的模式

\b(?:lower|upper) quartile \d+(?:,\d+)?\b
  • b防止部分匹配的单词边界
  • (?:lower|upper) quartile 匹配其中一个备选方案,然后quartile
  • \d+(?:,\d+)?将1+个数字与可选的小数部分匹配
  • \b单词边界

见aregex demo或aPython demo

import re
 
pattern = r"\b(?:lower|upper) quartile \d+(?:,\d+)?\b"
s = "(....) partijen waarvan de lower quartile 0,68% bedraagt en de upper quartile 2,06%."
 
print(re.findall(pattern, s))

输出

['lower quartile 0,68', 'upper quartile 2,06']

相关问题 更多 >