【问题标题】:how to replace uppercase and lowercase letters in words alternately in a sentence? Python如何在一个句子中交替替换单词中的大写和小写字母? Python
【发布时间】:2022-01-11 04:33:03
【问题描述】:

我是 Python 编程新手。我正在尝试了解列表。

我想创建一个新程序,可以将句子中的每个单词交替转换为大写和小写字母。

我被困在这里:

input_text = "hello my name is rahul and i'm from india"
result = ""
myArr = input_text.split(' ')

for idx in range(len(myArr)):
  if idx % 2 == 0 :
    result = result + myArr[idx].upper()
  else:
    result = result + myArr[idx].lower()

print(str(result))

通过这段代码我可以得到,例如:

input : "hello my name is rahul and i'm from india"
output : "HELLOmyNAMEisRAHULandI'MfromINDIA"

但我想要得到的是:

input : "hello my name is rahul and i'm from india"
output : "HELLO my NAME is RAHUL and I'M from INDIA"

我想为句子中的每个单词添加一个空格。

【问题讨论】:

    标签: python arrays list uppercase lowercase


    【解决方案1】:

    你已经明白了——最好的方法是将大写/小写的单词添加到列表中,然后使用.join() 将单词列表转换为字符串,每个单词用空格分隔:

    input_text = "hello my name is rahul and i'm from india"
    result = ""
    myArr = input_text.split(' ')
    words = []
    for idx in range(len(myArr)):
      if idx % 2 == 0 :
        words.append(myArr[idx].upper())
      else:
        words.append(myArr[idx].lower())
    
    result = ' '.join(words)
    print(result)
    

    与其他回答者的建议相反,using repeated concatenation is a bad idea for efficiency reasons

    【讨论】:

    • 嘿,谢谢!它奏效了,它真的帮助了我。
    • result 已经是str,所以最后一条语句应该只是-print(result) 不需要再次转换为字符串。
    • 你是对的。已编辑。
    【解决方案2】:

    我们可以尝试使用列表推导:

    input_text = "hello my name is rahul and i'm from india"
    words = input_text.split()
    output = ' '.join([x.upper() if ind % 2 == 0 else x for ind, x in enumerate(words)])
    print(output)  # HELLO my NAME is RAHUL and I'M from INDIA
    

    【讨论】:

      【解决方案3】:

      您可以将所有值添加到列表中,最后使用str.join 方法将它们连接起来。

      input_text = "hello my name is rahul and i'm from india"
      result = []
      myArr = input_text.split(' ')
      
      for idx in range(len(myArr)):
          if idx % 2 == 0:
              res = myArr[idx].upper()
          else:
              res = myArr[idx].lower()
          result.append(res)
      
      print(" ".join(result))
      

      输出:

      HELLO my NAME is RAHUL and I'M from INDIA
      

      【讨论】:

      • 嘿,谢谢!它奏效了,它真的帮助了我。
      【解决方案4】:

      除了其他答案之外,我在这里使用enumerate 提供了另一种类型的答案(请参阅https://www.geeksforgeeks.org/enumerate-in-python/),它使用其索引循环列表(或元组):

      input_text = "hello my name is rahul and i'm from india"
      
      result = []
      for idx, word in enumerate(input_text.split()):
          result.append(word.upper() if idx % 2 == 0 else word.lower())
      print(' '.join(result))
      

      使用列表理解,答案也可以像这样更短(参见if/else in a list comprehension

      input_text = "hello my name is rahul and i'm from india"
      
      result = [word.upper() if idx % 2 == 0 else word.lower() for idx, word in enumerate(input_text.split())]
      print(' '.join(result))
      

      这对你的 Python 生活很有帮助:)

      【讨论】:

        【解决方案5】:

        我已在您要附加到列表的位置添加空间:

        input_text = "hello my name is rahul and i'm from india"
        result = ""
        myArr = input_text.split(' ')
        
        for idx in range(len(myArr)):
            if idx % 2 == 0 :
                result = result + myArr[idx].upper() + " "  # added a space
            else:
                result = result + myArr[idx].lower() + " "  # added a space
        
        print(str(result))
        

        这给出了:

        HELLO my NAME is RAHUL and I'M from INDIA 
        

        【讨论】:

        • 嘿,谢谢!它奏效了,它真的帮助了我。
        【解决方案6】:

        你可以在添加每个单词后在结果中添加一个空格,即

        result = result + ' '
        

        这也会在字符串的末尾添加一个空格,这可能是不可取的。您可以使用 rstrip() 函数将其删除:

        result = result.rstrip()
        

        顺便说一句,result 已经是一个字符串,所以你不需要将它转换为一个字符串来打印语句。

        所以,把它们放在一起:

        input_text = "hello my name is rahul and i'm from india"
        result = ""
        myArr = input_text.split(' ')
        
        for idx in range(len(myArr)):
          if idx % 2 == 0 :
            result = result + myArr[idx].upper()
          else:
            result = result + myArr[idx].lower()
          result = result + ' '
        
        result = result.rstrip()    
        
        print(result)
        

        【讨论】:

        • 嘿,谢谢!它奏效了,它真的帮助了我。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-11
        • 2011-12-18
        • 2013-05-21
        • 1970-01-01
        • 2019-09-30
        • 1970-01-01
        • 2019-06-06
        相关资源
        最近更新 更多