如何优雅实现iscapitalized()函数检测字符串首字母是否大写?
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
wordvariable, 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
Falsefor strings starting with non-alphabetic characters (like numbers or symbols), which is the expected behavior.
内容的提问来源于stack exchange,提问作者user9674728

