如何在Python字符串

时间:2018-03-19 09:22:10

标签: 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"
]

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

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

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"

知道我该怎么做?

1 个答案:

答案 0 :(得分:1)

你快到了。在正则表达式中使用5使用\d+而不是硬编码:

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)