Str.contains(),其中字符串的一部分是可变的



我正在使用一个在比赛中包含回合的旧游戏。我需要找到指定"x的x的整数"的输出字符串。所以我可以根据回合执行地图调整。

在这种情况下,有12轮,所以这一行总是"12的x轮"。此外,脚本还对每个输入进行测试,以确定它是否符合给定的标准。但是,有多行以"round"开头,所以我决定安全起见,测试整行。

因此,我需要在确定的结果中添加一个变量结果:

if line.contains("Round [variable] of 12")

这在Python中可能吗?也许用正则表达式?我考虑过使用[0-9]{2}之类的东西,但由于变量可以是一个或两个数字,这将是不可靠的。

我认为你可以分两步完成。

round_variable = ("Round " + variable + "of 12")
if line.contains(round_variable):

另外,如果变量是整数,则可能需要将其设置为字符串:

if line.contains("Round " + str(variable) + " of 12")

用于在字符串中搜索模式,如:"This is (dd) round of 12"您可以使用正则表达式:

import re 
pattern = r'This is (dd) round of 12'
search_re = re.compile(pattern)
string = "This is 00 round of 12"
result = search_re.search(string)
if result :
print(result.groups())
round = result.groups()[0]
print("Round is ",round)

大部分代码是不言自明的。注意:如果您使用第1轮而不是第01轮,则此代码无法处理输入。因此,我们可以修改代码以匹配string中的此模式并返回该代码。

import re 
def checkpattern(string):
pattern1 = r'This is (d) round of 12'
pattern2 = r'This is (dd) round of 12'
search_re1 = re.compile(pattern1)
search_re2 = re.compile(pattern2)
result1 = search_re1.search(string)
if result1:
print(result1.groups())
round = result1.groups()[0]
print("Round is ",round)
return int(round)
result2 = search_re2.search(string)
if result2:
print(result2.groups())
round = result2.groups()[0]
print("Round is ",round)
return int(round)
def main():
string = "Hello This is 0 round of 12"
round = checkpattern(string)

main()

我是这样做的:Line只是输入的一个例子。

>>> line = "Round 10 of 12"
>>> if re.search(r"Rounds(d)+sofs12", line):
...     print("Validation successful")
...
Validation successful
>>> line = "Round 4 of 12"
>>> if re.search(r"Rounds(d)+sofs12", line):
...     print("Validation successful")
...
Validation successful

按照你的代码:

def roundfetch(roundline):
if re.search(r"Rounds(d)+sofs12", roundline):
return(int(re.search(r"Rounds(d)+sofs12", roundline).group(1)))

最新更新