相关文章推荐
朝气蓬勃的春卷  ·  python ...·  2 天前    · 
爽快的大熊猫  ·  C++ ...·  5 月前    · 
爱看书的卤蛋  ·  Flutter - ...·  1 年前    · 

python 查找字符串中的字符串

在 Python 中,你可以使用字符串的 find() index() 方法来查找一个字符串中是否包含另一个字符串。

这两种方法的不同之处在于,当目标字符串不存在于原始字符串中时, find() 方法会返回 -1 ,而 index() 方法会抛出 ValueError 异常。

以下是使用 find() index() 方法来查找字符串的示例代码:

string = "Hello, World!"
# 使用 find() 方法查找子字符串
if string.find("World") != -1:
    print("Found 'World' in the string.")
# 使用 index() 方法查找子字符串
try:
    string.index("World")
    print("Found 'World' in the string.")
except ValueError:
    print("'World' not found in the string.")

如果你想查找字符串中的所有子字符串,可以使用正则表达式或者字符串的 split() 方法。

例如,下面的代码使用正则表达式来查找字符串中所有的单词:

import re
string = "Hello, World! How are you today?"
words = re.findall(r'\w+', string)
print(words)

或者,你可以使用字符串的 split() 方法来将字符串按照指定的分隔符分割成多个子字符串,然后遍历这些子字符串,找到包含目标子字符串的子字符串:

string = "Hello, World! How are you today?"
words = string.split()
for word in words:
    if "World" in word:
        print(f"Found 'World' in '{word}'.")

以上就是在 Python 中查找字符串中的字符串的方法。希望这些信息能帮到你!

  •