【问题标题】:Convert titlecase words in the string to lowercase words将字符串中的大写单词转换为小写单词
【发布时间】:2018-08-06 10:25:53
【问题描述】:

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

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()

我还检查了相关问题Check if string is upper, lower, or mixed case in Python.。我想遍历我的数据框以及满足此条件的每个单词。

【问题讨论】:

    标签: python string lowercase


    【解决方案1】:

    您可以使用str.istitle()来检查您的单词是否代表titlecased字符串,即单词的第一个字符是否为大写,其余字符是否为小写。

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

    1. 使用str.split()将字符串转换为单词列表
    2. 使用str.istitle()str.lower() 进行所需的转换(我正在使用列表理解 来迭代列表并生成所需格式的新单词列表)时间>
    3. 使用str.join() 将列表连接回字符串:

    例如:

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

    【讨论】:

      【解决方案2】:

      你可以定义你的 transform 函数

      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()])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-15
        • 2018-08-29
        • 1970-01-01
        • 2016-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多