如何在Python中使用find()函数从字符串中提取子串?

huangapple go评论72阅读模式
英文:

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。该函数返回一组匹配项。您可以从组中选择一个,或者遍历该组并根据您的需求选择其中的内容。

以下是查找两个指定字符qo之间子字符串的示例:

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)

huangapple
  • 本文由 发表于 2023年2月26日 22:08:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572542.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定