大话性能 python 新手学习-Python 判断字符串中是否是中英文文小技巧

大话性能 · October 13, 2023 · 2849 hits

前言

工作中刚好用到了 Python 检测中英文文的小技巧,记录一下
更多内容可以学习《测试工程师 Python 工具开发实战》书籍《大话性能测试 JMeter 实战》书籍

一、检验是否全是中文字符
二、检验是否含有中文字符
三、检测是否全是英文字符
四、检测是否含有英文字符

一、检验是否全是中文字符

def is_all_chinese(strs):
    for _char in strs:
        if not '\u4e00' <= _char <= '\u9fa5':
            return False
    return True


print(is_all_chinese("hello"))
print(is_all_chinese("hello你好"))
print(is_all_chinese("123456"))
print(is_all_chinese("你好"))

输出结果:

False
False
False
True

二、检验是否含有中文字符

def is_contains_chinese(strs):
    for _char in strs:
        if '\u4e00' <= _char <= '\u9fa5':
            return True
    return False


print(is_contains_chinese("hello"))
print(is_contains_chinese("hello你好"))
print(is_contains_chinese("123456"))
print(is_contains_chinese("你好"))

输出结果:

False
True
False
True

三、检测是否全是英文字符

def is_all_english(strs):
    import string
    for i in strs:
        if i not in string.ascii_lowercase + string.ascii_uppercase:
            return False
    return True


print(is_all_english("hello"))
print(is_all_english("hello你好"))
print(is_all_english("123456"))
print(is_all_english("你好"))

输出结果:

True
False
False
False

四、检测是否含有英文字符

import re
def is_contains_english(str):
    my_re = re.compile(r'[A-Za-z]', re.S)
    res = re.findall(my_re, str)
    if len(res):
        return True
    else:
        return False


print(is_contains_english("hello"))
print(is_contains_english("hello你好"))
print(is_contains_english("123456"))
print(is_contains_english("你好"))

输出结果:

True
True
False
False
更多内容可以学习《测试工程师 Python 工具开发实战》书籍《大话性能测试 JMeter 实战》书籍

No Reply at the moment.
需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up