# 定义原始字符串string1="欢迎来到Python开发世界!"# 定义要查找的子字符串substring="Python"# 方法1:使用 in 关键字ifsubstringinstring1:print("包含!")else:print("不包含!")# 方法2:使用 str.find() 方法ifstring1.find(substring)!=-1:print("包含!")else:print("不包含!")# 方法3:使用 str....
stringexample="Kiki"substring="ki"ifstringexample.find("ki")!=-1:print("We've found the string!")else:print("Oops, not found!") 1. 2. 3. 4. 5. 6. 其运行结果仍为: 复制 We've found the string! 1. 方法3:使用 Contains 方法 __contains__() 是另外一种可以检查字符串包含的方法。
Python提供了多种方法来完成这一点,一种简单的方法是使用str.find()方法。 AI检测代码解析 # 使用循环查找所有位置start=0# 初始查找位置whileTrue:# 查找子字符串在主字符串中的位置start=main_string.find(sub_string,start)# 如果没有找到,退出循环ifstart==-1:break# 存储找到的位置positions.append(start)...
result = quote.find('let it') print("Substring 'let it':", result)# find returns -1 if substring not found result = quote.find('small') print("Substring 'small ':", result)# How to use find() if(quote.find('be,') !=-1): print("Contains substring 'be,'")else:print("Doesn...
Check if Python StringContains SubstringUsing in operator The ‘in’ operator function in Python can check if a Python string contains a substring. This is the easiest way. It returns a boolean value, like true or false. Example: originalString = "pythonknowledge" ...
Get Your Code:Click here to download the free sample codethat you’ll use to check if a string contains a substring. Take the Quiz:Test your knowledge with our interactive “How to Check if a Python String Contains a Substring” quiz. You’ll receive a score upon completion to help you...
将String 变量转换为 float、int 或 boolean 向字符串填充或添加零的不同方法 去掉字符串中的 space 字符 生成N个字符的随机字符串 以不同的方式反转字符串 将Camel Case 转换为 Snake Case 并更改给定字符串中特定字符的大小写 检查给定的字符串是否是 Python 中的回文字符串 ...
Using the find() Method Another way to check if a string contains a substring in Python is by using thefind()method. It returns the index of the first occurrence of the substring within the string. If the substring is not found, it returns -1. Here’s an example: ...
print(str.__contains__('ABC', 'D')) Output: True False Let’s look at another example where we will ask the user to enter both the strings and check if the first string contains the second string or substring or not. input_str1 = input('Please enter first input string\n') ...
如果您对查找字符串中子字符串的位置更感兴趣(而不是简单地检查是否包含子字符串),那么find()字符串方法可能会更有帮助。 代码语言:javascript 代码运行次数:0 运行 AI代码解释 s='Does this string contain a substring?'print('\'string\' location -> {}'.format(s.find('string')))print('\'spring\...