繁体   English   中英

如何在Python字符串中查找子字符串

[英]How to find substring in Python string

我有一个字符串列表,如下所示:

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"
]

我希望能够从这些字符串中查找并替换子字符串。

我可以按以下方式查找和替换它(如果我有要替换的字符串):

new_total = "total = 20"
for str in strings:
  new_string = re.sub(r"total\s?=\s?5", "{}".format(new_total), str)
  print(new_string)

在这种情况下,它仅匹配total=5 这不是我想要的。

我想首先从一个句子中提取total = <value> ,无论它在=号之前还是之后都有空格,然后将提取的值插入其他句子中

因此,如下所示:

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)

输出应为:

"On monday we had total=20 cars",
"On tuesday we had total=20 cars",
"On wensdsday we are going to have total=20 or maybe less cars"

知道我该怎么做吗?

你快到了 在正则表达式中使用\\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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM