如何检查字符串是否符合Sentence Case格式?
如何检查字符串是否符合Sentence Case格式
根据你给出的示例,这里的Sentence Case判定规则是:
- 字符串首字符必须为大写字母
- 除首字符外,所有字母字符必须是小写(空格、数字、标点等非字母内容不影响判定)
实现代码
def check_string(string): # 处理空字符串 if not string: return False # 检查首字符是否为大写字母 if not string[0].isupper(): return False # 遍历剩余字符,验证所有字母都是小写 for char in string[1:]: if char.isalpha() and not char.islower(): return False return True
测试验证
print(check_string('This is a proper sentence case.')) # 输出: True print(check_string('THIS IS UPPER CASE')) # 输出: False print(check_string('This string is Clean')) # 输出: False
逻辑说明
- 先处理空字符串的特殊情况,避免后续索引报错
- 首字符必须是大写字母,不符合直接返回
False - 遍历字符串剩余部分,只要发现有字母是大写,就返回
False - 所有检查通过则返回
True
补充边界测试
print(check_string('Hello!')) # 输出: True print(check_string('hello')) # 输出: False print(check_string('Hello world 123')) # 输出: True print(check_string('Hello World')) # 输出: False
内容的提问来源于stack exchange,提问作者Mdick
相关产品推荐
相关产品推荐

