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

如何检查字符串是否符合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

逻辑说明

  1. 先处理空字符串的特殊情况,避免后续索引报错
  2. 首字符必须是大写字母,不符合直接返回False
  3. 遍历字符串剩余部分,只要发现有字母是大写,就返回False
  4. 所有检查通过则返回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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:35:29