You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现仅接受大写字母和数字的输入?

Fixing Input Validation for Letters & Numbers Only

Hey there! Let’s sort out this input validation issue you’re facing. Your current code has a couple of quirks that prevent it from properly blocking forbidden characters—let’s break down the problem and fix it.

What’s Wrong with Your Current Code?

Your nested loops have a logic flaw: once it finds a character in ch that doesn’t match a forbidden character, it hits else: break, which stops checking the rest of the forbidden characters. This means it might miss other invalid symbols in the input. Plus, when you ask for a new input, it doesn’t re-run the full check on the new entry, so invalid characters could still slip through.

Solution 1: Use Python’s Built-in isalnum() (Simplest Approach)

Python has a handy string method isalnum() that checks if every character in a string is either a letter or a number—exactly what you need! Combine this with a loop that keeps asking for input until it’s valid:

while True:
    ch = input("Please enter only letters and numbers: ").upper()
    if ch.isalnum():
        break  # Exit the loop when input is valid
    print("Invalid input! Please use only uppercase letters and numbers.")

# Now 'ch' holds a valid input with only letters/numbers
print(f"Valid input received: {ch}")

How This Works:

  • The while True loop runs indefinitely until we hit break.
  • input(...).upper() converts the user’s input to uppercase right away.
  • ch.isalnum() returns True only if all characters are letters (a-z, A-Z) or numbers (0-9)—automatically excluding all those forbidden symbols you listed.

Solution 2: Manual Forbidden Character Check (For Custom Rules)

If you ever need to adjust the forbidden character list later, you can explicitly check for forbidden symbols using any():

forbidden_chars = "!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"

while True:
    ch = input("Please enter only letters and numbers: ").upper()
    # Check if any character in 'ch' is in the forbidden list
    has_invalid_char = any(char in forbidden_chars for char in ch)
    if not has_invalid_char:
        break
    print("Invalid input! No special characters allowed—only letters and numbers.")

print(f"Valid input received: {ch}")

How This Works:

  • any(...) checks if at least one character in ch is present in forbidden_chars.
  • If no invalid characters are found (not has_invalid_char), we exit the loop.

Either of these approaches will reliably enforce your input rules. The first method is cleaner for your specific use case since isalnum() handles exactly what you need without maintaining a separate forbidden list.

内容的提问来源于stack exchange,提问作者MEMER

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:26:00