1. 使用 `find()` 方法:
s = 'Hello, World!'
substring = 'World'
start = s.find(substring)
if start != -1:
extracted_string = s[start:]
print(extracted_string) 输出 'World!'
else:
print('Substring not found')
2. 使用 `index()` 方法:
s = 'Hello, World!'
substring = 'World'
try:
start = s.index(substring)
extracted_string = s[start:]
print(extracted_string) 输出 'World!'
except ValueError:
print('Substring not found')
3. 使用 `rfind()` 方法:
s = 'Hello, World!'
substring = 'World'
start = s.rfind(substring)
if start != -1:
extracted_string = s[start:]
print(extracted_string) 输出 'World!'
else:
print('Substring not found')
4. 使用 `rindex()` 方法:
s = 'Hello, World!'
substring = 'World'
start = s.rindex(substring)
if start != -1:
extracted_string = s[start:]
print(extracted_string) 输出 'World!'
else:
print('Substring not found')
5. 使用 `in` 关键字:
s = 'Hello, World!'
substring = 'World'
if substring in s:
print('Substring found')
else:
print('Substring not found')
6. 使用正则表达式(`re` 模块):
import re
s = 'Hello, World!'
pattern = r'World'
match = re.search(pattern, s)
if match:
print('Substring found at position:', match.start())
else:
print('Substring not found')
以上方法都可以用来查找字符串中的指定子字符串。选择哪种方法取决于你的具体需求,例如是否需要从字符串的特定位置开始查找,或者是否需要处理复杂的模式匹配