Python find() 函数应用:查找、替换、截取和检查字符串
Python 中的 find() 函数用于查找字符串中是否包含指定的子字符串,如果包含则返回子字符串在字符串中的开始位置,否则返回 -1。下面是一些 find() 函数的应用场景:
- 检查字符串中是否包含特定的关键字
text = 'Python is a popular programming language'
if text.find('programming') != -1:
print('The text contains the keyword 'programming'')
else:
print('The text does not contain the keyword 'programming'')
- 替换字符串中的部分内容
text = 'Python is a popular programming language'
new_text = text.replace('programming', 'scripting')
print(new_text)
- 截取字符串中的一部分内容
text = 'Python is a popular programming language'
start = text.find('popular')
end = text.find('language')
new_text = text[start:end]
print(new_text)
- 检查字符串是否以特定的前缀或后缀开头或结尾
text = 'Python is a popular programming language'
if text.startswith('Python'):
print('The text starts with 'Python'')
if text.endswith('language'):
print('The text ends with 'language'')
- 检查字符串中是否包含特定的字符序列
text = 'Python is a popular programming language'
if 'pro' in text:
print('The text contains the character sequence 'pro'')
else:
print('The text does not contain the character sequence 'pro'')
原文地址: https://www.cveoy.top/t/topic/oYCN 著作权归作者所有。请勿转载和采集!