Python 将字符串中的标题文字转换为小写文字

Python 将字符串中的标题文字转换为小写文字,python,string,lowercase,Python,String,Lowercase,我想将字符串中的所有标题文字(以大写字符开头,其余字符为小写的文字)转换为小写字符。例如,如果我的初始字符串是: text = " ALL people ARE Great" 我希望结果字符串为: "ALL people ARE great" 我尝试了以下方法,但不起作用 text = text.split() for i in text: if i in [word for word in a if not word.islower() and not word.isu

我想将字符串中的所有标题文字(以大写字符开头,其余字符为小写的文字)转换为小写字符。例如,如果我的初始字符串是:

text = " ALL people ARE Great"
我希望结果字符串为:

 "ALL people ARE great"
我尝试了以下方法,但不起作用

text = text.split()

for i in text:
        if i in [word for word in a if not word.islower() and not word.isupper()]:
            text[i]= text[i].lower()
我还查了相关问题。我希望迭代我的数据帧,并为每个符合此条件的单词迭代

您可以使用检查您的单词是否表示基于标题的字符串,即单词的第一个字符是否为大写,其余字符是否为小写

为了获得您想要的结果,您需要:

  • 使用以下命令将字符串转换为单词列表
  • 使用and进行所需的转换(我使用列表理解迭代列表并生成所需格式的新单词列表)
  • 使用as将列表连接回字符串:
  • 例如:

    >>> text = " ALL people ARE Great"
    
    >>> ' '.join([word.lower() if word.istitle() else word for word in text.split()])
    'ALL people ARE great'
    
    您可以使用检查您的单词是否表示基于标题的字符串,即单词的第一个字符是否为大写,其余字符是否为小写

    为了获得您想要的结果,您需要:

  • 使用以下命令将字符串转换为单词列表
  • 使用and进行所需的转换(我使用列表理解迭代列表并生成所需格式的新单词列表)
  • 使用as将列表连接回字符串:
  • 例如:

    >>> text = " ALL people ARE Great"
    
    >>> ' '.join([word.lower() if word.istitle() else word for word in text.split()])
    'ALL people ARE great'
    

    您可以定义
    转换
    函数

    def transform(s):
        if len(s) == 1 and s.isupper():
            return s.lower()
        if s[0].isupper() and s[1:].islower():
            return s.lower()
        return s
    
    text = " ALL people ARE Great"
    final_text = " ".join([transform(word) for word in text.split()])
    

    您可以定义
    转换
    函数

    def transform(s):
        if len(s) == 1 and s.isupper():
            return s.lower()
        if s[0].isupper() and s[1:].islower():
            return s.lower()
        return s
    
    text = " ALL people ARE Great"
    final_text = " ".join([transform(word) for word in text.split()])