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

如何优雅实现iscapitalized()函数检测字符串首字母是否大写?

Better Ways to Implement iscapitalized() in Python

Absolutely—writing out 26 if-else checks is not just tedious, it’s also against the DRY (Don’t Repeat Yourself) principle. There are several clean, concise ways to implement this function properly. Let’s go through the best options:

1. Use str.isupper() on the first character

This is the most straightforward approach. The isupper() method natively checks if a character is an uppercase letter. We just need to handle the edge case of an empty string to avoid an index error:

def iscapitalized(word):
    # Return False if the string is empty
    if not word:
        return False
    # Check if the first character is uppercase
    return word[0].isupper()

# Usage
word = input('Enter a word: ')
print(iscapitalized(word))

2. Compare the first character to its uppercase version

Another simple method: convert the first character to uppercase and see if it matches the original. This works because if the character was already uppercase, converting it won’t change it:

def iscapitalized(word):
    if not word:
        return False
    return word[0] == word[0].upper()

# Usage
word = input('Enter a word: ')
print(iscapitalized(word))

3. Use string.ascii_uppercase with startswith()

If you prefer using startswith() (like your original code), leverage the string module’s pre-defined ascii_uppercase constant—it contains all 26 uppercase letters. Pass it as a tuple to startswith() since the method accepts multiple prefixes:

import string

def iscapitalized(word):
    return word.startswith(tuple(string.ascii_uppercase))

# Usage
word = input('Enter a word: ')
print(iscapitalized(word))

Important Notes:

  • Avoid global variables: Your original function uses a global word variable, which makes the function less reusable. It’s better to pass the word as an argument, as shown in all examples above.
  • Return booleans instead of printing: Having the function return a boolean value means you can use it in other parts of your code (like conditionals) instead of just printing the result immediately.
  • Edge cases: All these methods handle empty strings correctly, and will return False for strings starting with non-alphabetic characters (like numbers or symbols), which is the expected behavior.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:22:49