Python小技巧:判断输入是否为汉字/英文/数字

Python判断输入是否为汉字/英文/数字

在这里插入图片描述

1. 判断输入是否为汉字

定义函数is_chinese,输入为字符串,该函数通过遍历字符串中的每个字符:

  • 如果字符的Unicode编码不在汉字的范围内,说明输入不全是汉字,函数返回False
  • 如果遍历完所有字符都在汉字的范围内,说明输入全是汉字,函数返回True
def is_chinese(input_string):
    for char in input_string:
        if not ('\u4e00' <= char <= '\u9fff'):
            return False
    return True

e.g.

input1 = "中国"
input2 = "Hello, 世界"
input3 = "1234"

print(is_chinese(input1))  # True
print(is_chinese(input2))  # False
print(is_chinese(input3))  # False

输出
True
False
False

2. 判读是否为英文

方法一:

定义函数is_english,输入为字符串,该函数通过遍历字符串中的每个字符:

  • 如果字符不在英文的范围内,说明输入不全是英文,函数返回False
  • 如果遍历完所有字符都在英文的范围内,说明输入全是英文,函数返回True
def is_english(word):
    for char in word:
        if not ('a' <= char <= 'z' or 'A' <= char <= 'Z'):
            return False
    return True

e.g.

input1 = "中国"
input2 = "HelloWord"
input3 = "1234"

print(is_english(input1))  # False
print(is_english(input2))  # True
print(is_english(input3))  # False

输出

False
True
False

方法二:
定义函数is_english_regex,输入为字符串,该函数通过使用正则表达式进行判断:

  • 如果字符不全是英文,函数返回False
  • 如果字符全是英文,函数返回True
import re
def is_english_regex(word):
    pattern = re.compile(r'^[a-zA-Z]+$')
    return bool(pattern.match(word))

3. 判断是否为数字

(1)判断输入字符串是否为数字

定义函数is_number,输入为字符串,通过尝试将其转换为浮点数:

  • 如果转换成功,说明输入是数字,函数返回True。
  • 如果转换失败,说明输入不是数字,函数返回False。
def is_number(input_string):
    try:
        float(input_string)
        return True
    except ValueError:
        return False

e.g.

input1 = "123"
input2 = "3.14"
input3 = "hello"

print(is_number(input1))  # True
print(is_number(input2))  # True
print(is_number(input3))  # False

输出

True
True
False

(2)判断输入字符串的每个字符是否都为数字

定义函数is_number,输入为字符串,通过直接调用isdigit方法,对其进行判断:

  • 如果每个字符都是数字,函数返回True。
  • 如果存在不是数字的字符,函数返回False。
def is_number(input_string):
    if input_string.isdigit():
        return True
    return False

e.g.

input1 = "123"
input2 = "3.14"
input3 = "hello"

print(is_number(input1))  # True
print(is_number(input2))  # True
print(is_number(input3))  # False

输出
True
False
False

猜你喜欢

转载自blog.csdn.net/apr15/article/details/129904230