if notsomestring.contains("blah"): continue 您可以使用in操作员: if "blah" not insomestring: continue 如果它只是一个子字符串搜索,你可以使用string.find("substring")。 你必须与小心一点find,index和in虽然,因为它们是字符串搜索。换句话说,这个: s= "This be a string" ifs.find("is") == -1...
STRINGstringtextstringsubstringMATCHESintindexcontains 完整代码示例 将上述步骤和代码整合在一起,我们得到了完整的代码: text="这是一个测试字符串示例"substring="测试"matches=[]# 用于存储匹配的索引# 遍历字符串中的每一个字符foriinrange(len(text)):# 检查子串是否匹配iftext[i:i+len(substring)]==substr...
示例用法:string.index(sub) isalnum(self):无参数,判断字符串是否由字母和数字组成。示例用法:string.isalnum() isalpha(self):无参数,判断字符串是否只包含字母。示例用法:string.isalpha() isascii(self):无参数,判断字符串是否只包含ASCII字符。示例用法:string.isascii() isdecimal(self):无参数,判断字符串是否...
Note that find() function returns the index position of the substring if it’s found, otherwise it returns -1. count() functionto find the number of occurrences of a substring in the string. s = 'My Name is Pankaj' print('Substring count =', s.count('a')) s = 'This Is The Bes...
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: ...
.index() Method .count() Method .replace Method Interactive Example If you are looking to find or replace items in a string, Python has several built-in methods that can help you search a target string for a specified substring. .find() Method Syntax string.find(substring, start, end) ...
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...
The python str class has a __contains__() method that will check if a python string contains a substring. It will return true if it’s found and will return false if it’s not. You will notice that the method name is wrapped in two underscores. This prevents this method from being ...
ValueError: substring not found >>> str.index("n") #同find类似,返回第一次匹配的索引值 4 >>> str.rindex("n") #返回最后一次匹配的索引值 11 >>> str.count('a') #字符串中匹配的次数 0 >>> str.count('n') #同上 2 >>> str.replace('EAR','ear') #匹配替换 'string learn' >...
print(str.__contains__('ABC', 'D')) Output: 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') ...