python-3.x - 为什么 isalpha() 不能清理用户输入?
问题描述
我在这里遇到的问题是该isalpha()
功能没有做它应该做的事情,用户能够发送包含非字母字符的消息。我不确定为什么会发生这种情况。在假设我的代码中存在逻辑错误之前,我假设这是某种托管问题(看起来不是),但从逻辑上讲,这对我来说可能是错误的?我还假设它与函数不是异步的有关,我不知道我可能正在使用那个。
import discord
from discord.ext import commands
import re
class Shiritori(commands.Cog):
""" Start a new word from the last letter of the one before. """
def __init__(self, client):
self.client = client
self.repeats = re.compile(r'(.)\1{2,}') # Matches spam like 'eeeeeee'
self.shiritori_channel = 578788555120312330 # Official
@commands.Cog.listener()
async def on_message(self, message):
try:
if message.channel.id == self.shiritori_channel:
previous_message = (await message.channel.history(limit=2).flatten())[1].content
repeats_mo = self.repeats.search(message.content)
if not repeats_mo and message.content.isalpha():
if previous_message[-1].lower() != message.content[0].lower():
await message.author.send(
f'Your message must start with the last letter of the latest message!')
await message.delete()
else:
await message.author.send("You can't do that here!")
await message.delete()
except discord.Forbidden:
await message.delete()
解决方案
我猜您期望任何非 ascii 英文字符都不是 alpha。
但
根据文档,
str.isalpha() 如果字符串中的所有字符都是字母并且至少有一个字符,则返回 True,否则返回 False。字母字符是在Unicode 字符数据库中定义为“字母”的字符,即一般类别属性为“Lm”、“Lt”、“Lu”、“Ll”或“Lo”之一的字符。请注意,这与 Unicode 标准中定义的“字母”属性不同。
所以例如à
(french a) orлюбовь
也被考虑alpha
'à'.isalpha()
True
'любовь'.isalpha()
True
如果你想要英文字母,请使用isascii()
:
'à'.isascii()
False
推荐阅读
- uitableview - SfTabView 标题剪辑缩放图像
- javascript - 如何使用 Google 跟踪代码管理器(而不是 gtag.js)为酒店广告系列设置转化跟踪?
- java - 有没有办法使用度数变化来绘制曲线?
- c++ - 通用线程池类无法正常工作
- typescript - 是否可以在 TypeScript 中递归地推断泛型类型?
- python - 如何在python中正确预白时间序列
- python - 在 pyinstaller 中使用 base_library.zip 文件
- android - 如何从我的资产文件夹中访问 .docx 文件?
- r - 在 R 中使用绑定 tf_df
- python-3.x - 子类的父类中的参数使用什么类型提示?