判断是否字母的问题

2020-08-30 18:27:22 +08:00
 songdg
网上找的一个函数,为什么不能判断大写字母
def is_alphabet(uchar):
"""判断一个 unicode 是否是英文字母"""
if (uchar >= u'\u0041' and uchar<=u'\u005A') or (uchar >= u'\u0061' and uchar<=u'\u007A'):
return True
else:
return False
2151 次点击
所在节点    Python
9 条回复
imn1
2020-08-30 18:36:00 +08:00
什么意思?
is_alphabet('A') 返回 False 么?
skinny
2020-08-30 19:31:38 +08:00
Python 没有 char 类型
skinny
2020-08-30 19:35:25 +08:00
你一定要按这个函数的样子写,你用 chr 函数把单个字符转换成 int
baobao1270
2020-08-30 19:53:38 +08:00
(uchar >= u'\u0041' and uchar<=u'\u005A') 是 ASCII 大写字母 A-Z
(uchar >= u'\u0061' and uchar<=u'\u007A') 是 ASCII 小写字母 a-z
注释都说了,这个智能判断是否为字母,而不能判断是大写还是小写……
你这个写法也不够 Pythonic,可以写成
(u'\u0041' <= uchar <=u'\u005A') or (u'\u0061' <= uchar <=u'\u007A')

@skinny
Python 是可以直接比较字符串的 ASCII 值的

可以尝试以下代码:
from enum import Enum

class InAlphabetResult(Enum):
UpperCase = 1
LowerCase = 2
NotInAlphabet = 3

def in_alphabet(char):
if "a" <= char <= "z":
return InAlphabetResult.LowerCase
if "A" <= char <= "Z":
return InAlphabetResult.UpperCase
return InAlphabetResult.NotInAlphabet
baobao1270
2020-08-30 19:55:35 +08:00
缩进没了,我贴个链接吧
https://pastebin.ubuntu.com/p/MGZqgWGCSr/
songdg
2020-08-31 01:24:17 +08:00
@baobao1270 谢谢帮忙。
laike9m
2020-08-31 10:24:21 +08:00
你这完全没必要啊,直接标准库 isupper 函数就完了的事

https://docs.python.org/3.8/library/stdtypes.html#str.isupper
songdg
2020-09-02 09:24:45 +08:00
@laike9m 对,用标准库更方便。
biglazycat
2020-09-12 07:03:07 +08:00
def in_alphabet(char):
char = str(char)
if char.islower():
return 'LowerCase'
elif char.isupper():
return 'UpperCase'
else:
return 'NotInAlphabet'

print(in_alphabet('a'))
print(in_alphabet('A'))
print(in_alphabet(1))

写的很粗糙,目前的理解就写样了。请多多指教。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/702620

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX