如何在Python字符串中查找子字符串
我有一个字符串列表,如下所示:如何在Python字符串中查找子字符串,python,Python,我有一个字符串列表,如下所示: strings = [ "On monday we had total=5 cars", "On tuesday we had total = 15 cars", "On wensdsday we are going to have total=9 or maybe less cars" ] some_sentence = "We will use this sentence to get total=20 of cars." new_total =
strings = [
"On monday we had total=5 cars",
"On tuesday we had total = 15 cars",
"On wensdsday we are going to have total=9 or maybe less cars"
]
some_sentence = "We will use this sentence to get total=20 of cars."
new_total = "????" // it needs to get total=20
for str in strings:
// Here I want to replace `total=<value>` or `total = <value>` in every str with new_total
new_string = "????"
print(new_string)
我希望能够从这些字符串中找到并替换子字符串
我可以按如下方式查找并替换它(如果我有要替换的字符串):
在这种情况下,它只匹配total=5
。这不是我想要的
我想首先从一个句子中提取total=
,不管它在=
符号之前或之后是否有空格,然后将提取的值插入到其他句子中
因此,有如下情况:
strings = [
"On monday we had total=5 cars",
"On tuesday we had total = 15 cars",
"On wensdsday we are going to have total=9 or maybe less cars"
]
some_sentence = "We will use this sentence to get total=20 of cars."
new_total = "????" // it needs to get total=20
for str in strings:
// Here I want to replace `total=<value>` or `total = <value>` in every str with new_total
new_string = "????"
print(new_string)
你知道我该怎么做吗?你就快到了。在正则表达式中使用
\d+
代替硬编码的5
:
import re
strings = [
"On monday we had total=5 cars",
"On thursday we had total = 15 cars",
"On wendesday we are going to have total=9 or maybe less cars"
]
new_total = "total = 20"
for s in strings:
new_string = re.sub(r"total\s?=\s?\d+", "{}".format(new_total), s)
print(new_string)
# to extract the information you can use:
p = re.compile(r"(total\s?=\s?\d+)")
for s in strings:
print( p.findall(s) )
输出:
On monday we had total = 20 cars
On thursday we had total = 20 cars
On wendesday we are going to have total = 20 or maybe less cars
['total=5']
['total = 15']
['total=9']
如果您确定您将有一个匹配项,您也可以使用
p.search(s).group(0)
(它将返回字符串而不是列表)而不是p.findall(s)
,,如果您可以明确说明您想要做什么:“我想在=
周围添加空格-登录total=XXX
”。只需一小部分文字,您的问题就更容易理解。@Aran Fey我想从一个句子中获取子字符串some_-句子=“我们将使用这个句子来获取总计=20辆车。”
无论等号前后是否有空格。然后将其添加到字符串列表中的每个字符串中,而不是total=
或total=
Oh,那么您首先要从一个句子中提取total=XXX
,然后将提取的值插入到其他句子中?我现在明白了。但是你的问题在我看来非常不清楚。你应该试着澄清一下。(就像问题本身,而不是评论中一样。)@Aran Fey确实如此好啊但是我想从一个句子中得到total=
some_-sense=“我们将使用这句话获得总共20辆车。”
。如何从某个句子中获得total=20
?@Aran Fey如果您希望比赛前后的部分可以在单独的组中访问,那么*
部分是有用的。但我删除了它们,因为它们在这里真的不是必需的。