SoFunction
Updated on 2024-11-16

Python to determine whether the string is Chinese and English summary of tips

preamble

The blogger just happened to use the Python detection of Chinese and English text in the work of a small trick, record it!

I. Test whether all Chinese characters

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("Hello."))

Output results:

False
False
False
True

Second, test whether it contains Chinese characters

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("Hello."))

Output results:

False
True
False
True

III. Detecting whether all English characters

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("Hello."))

Output results:

True
False
False
False

IV. Detection of the presence of English characters

import re
def is_contains_english(str):
    my_re = (r'[A-Za-z]', )
    res = (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("Hello."))

Output results:

True
True
False
False

summarize

to this article on Python to determine whether the string is in English tips to this article, more related Python to determine the string is in English content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!