在Python中,判断字符串中是否包含特定字符或满足特定条件,可以通过以下几种方法实现:
1. 使用 `in` 运算符:
name = "mkyong is learning python 123"
if "python" in name:
print("found python!")
else:
print("nothing")
2. 使用 `str.find()` 方法:
name = "mkyong is learning python 123"
if name.find("python") != -1:
print("found python!")
else:
print("nothing")
3. 使用正则表达式(`re` 模块):
import re
zh_pattern = re.compile(u'[\u4e00-\u9fa5]+')
def contain_zh(word):
return zh_pattern.search(word) is not None
word1 = "ceshi,测试"
word2 = "ceshi,ceshi"
if contain_zh(word1):
print("{} 里面有中文".format(word1))
if contain_zh(word2):
print("{} 里面有中文".format(word2))
4. 使用字符串方法 `str.isalnum()`、`str.isalpha()`、`str.isdigit()` 等来判断字符串是否只包含数字、字母或两者混合:
str_1 = "123"
str_2 = "Abc"
str_3 = "123Abc"
print(str_1.isdigit()) True
print(str_2.isalpha()) True
print(str_3.isalnum()) True
5. 判断字符串是否全为中文:
def is_all_chinese(strs):
for _char in strs:
if not ('\u4e00' <= _char <= '\u9fa5'):
return False
return True
def is_contains_chinese(strs):
for _char in strs:
if ('\u4e00' <= _char <= '\u9fa5'):
return True
return False