在Python中获取两个其他字符串中间的字符串

2024-04-19 11:36:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在另外两个字符串之间找到该字符串。我怎么能这样做

string = "vHELLOv"

查找位于两个小写"v"之间的"HELLO"

另一个例子是:

string = "/World/"

在两个{{CD4>}s

的中间找到^ {CD3>}

Tags: 字符串helloworldstring例子小写cd3cd4
3条回答

试试这个。使用regex(正则表达式)库进行模式匹配

import re

# 1st pattern: vHELLOv
re.findall(r"v(.*?)v", "vHELLOv")


# 2nd pattern: /HELLO/
re.findall(r"/(.*?)/", "/HELLO/")

## NOTE: For regex in python you do not have to escape / with a \. 
#        But, if you want to use a similar regex universally elsewhere, 
#        consider escaping each / with a \.
#
#        Example: r"/(.*?)/" ==> r"\/(.*?)\/"

编辑:按照Jan的建议,在()中添加了惰性量词.*?,而不是.*

要删除标点符号,可以在Python中使用以下正则表达式:

import re
s = "/World/"
new_s = re.sub(r'\W', "", s)

如果您谈论的是围绕另一个字符串的两个相同字符串,则可以使用split方法:

string = "vHELLOv"
surrounder = "v"
x = string.split(surrounder)

print(x[1]) 

相关问题 更多 >