英文:
How to extract a substring from a string in Python with find()?
问题
在Python中,我有一个字符串,我需要从中提取一个子字符串。我需要提取的子字符串位于字符串中的两个特定字符之间。由于字符串的长度和值不确定,所以在特定点切片在这种情况下不起作用。我该如何实现这一点?
例如,假设我有字符串"The quick brown fox jumps over the lazy dog"。我想提取字符"q"和"o"之间的子字符串,即"uick br"。我该如何使用Python来实现这个目标?我尝试使用find()函数,但不确定一旦找到字符的位置,如何提取子字符串。
英文:
I have a string in Python, and I need to extract a substring from it. The substring I need to extract is between two specific characters in the string. The string is of indeterminate length and value, so slicing at specific points does not work in this case. How can I achieve this?
For example, suppose I have the string "The quick brown fox jumps over the lazy dog". I want to extract the substring between the characters "q" and "o", which is "uick br". How can I do this using Python? I've tried using the find() function, but I'm not sure how to extract the substring once I've found the positions of the characters.
答案1
得分: 1
如果您确定在两个指定字符之间至少存在一个子字符串,可以使用regex
函数,特别是search
。该函数返回一组匹配项。您可以从组中选择一个,或者遍历该组并根据您的需求选择其中的内容。
以下是查找两个指定字符q
和o
之间子字符串的示例:
str = "The quick brown fox jumps over the lazy dog"
sub = re.search("q(.+?)o", str).groups()[0]
print(sub)
英文:
If you sure there is at least one sub-string existing between two specified characters, it's able to use regex
functions, particularly search
. The function returns a group of matches. You can pick one from the group or travel through the group and select ones as your needs.
Below is an example of finding a substring between two specified characters q
and o
.
str = "The quick brown fox jumps over the lazy dog"
sub = re.search("q(.+?)o",str).groups()[0]
print(sub)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论