python 有没有一个函数可以得到字符串之间的字符串?

lnxxn5zx  于 2022-12-28  发布在  Python
关注(0)|答案(3)|浏览(140)
input = "{1} {John Travis} {was} {here}"

假设我想得到第二对和第三对括号内的字符串,那么预期的输出是:

output = "John Travis was"

我尝试使用以空格作为分隔符的数组拆分,预期结果如下:

array = ["{1}", "{John Travis}", "{was}", "{here}"]

array[1] = re.sub("{", "", array[1])
array[1] = re.sub("}", "", array[1])

array[2] = re.sub("{", "", array[2])
array[2] = re.sub("}", "", array[2])

#expected result: array[1] + array[2] ( "John Travis was" )

但我记得我在“John Travis”上有分隔符““,结果是:

array = ["{1}", "{John", "Travis}", "{was}", "{here}"]

array[1] = re.sub("{", "", array[1])
array[2] = re.sub("}", "", array[2])

array = ["{1}", "John", "Travis", "{was}", "{here}"]

#unexpected result: array[1] + array[2] ( "John Travis" )

如何进行?
谢谢你的倾听。

mec1mxoz

mec1mxoz1#

对于所需的输出,您可以使用regex:

import re

input = "{1} {John Travis} {was} {here}"

# Use a regular expression to match the pattern of the brackets and the content inside them
matches = re.findall(r'\{([^}]*)\}', input)

# Extract the second and third items in the list of matches
output = matches[1] + ' ' + matches[2]

print(output)

产出将是:

John Travis was
yzxexxkh

yzxexxkh2#

另一个解决方案(不使用re)是,可以用'替换{,用',替换},然后使用ast.literal_eval将string作为元组求值,然后使用标准索引:

from ast import literal_eval

s = "{1} {John Travis} {was} {here}"

s = literal_eval(s.replace("{", "'").replace("}", "',"))
print(s[1], s[2])

图纸:

John Travis was
f87krz0w

f87krz0w3#

使用列表解析的替代解决方法:

input = "{1} {John Travis} {was} {here}"
print(*[i.strip('{}') for i in input.split()[1:-1]])

# John Travis was

相关问题