【问题标题】:How to convert alphabets to capital letter from a list comprising of elements with alphanumeric and special characters in Python?python - 如何将包含Python中具有字母数字和特殊字符的元素的列表中的字母转换为大写字母?
【发布时间】:2021-10-30 06:17:59
【问题描述】:

我有一个列表,其中包含包含字母、数字和特殊字符的元素。我只想将字母转换为大写字母,如下所示:

List=["A34_rtXf $ t", "Artyx&-T7", 567, 543,"Aewr-075rJ"]

预期输出:

List=["A34_RTXF $ T", "ARTYX&-T7", 567, 543,"AEWR-075RJ"]

关于如何实现这一点的任何提示?

【问题讨论】:

    标签: python arraylist


    【解决方案1】:

    您可以通过listloop,如果项目属于type: str,则使用str.upper() 将项目的字母大写。

    一个班轮代码例如:

    [i.upper() if isinstance(i,str) else i for i in List]
    

    输出:

    ['A34_RTXF $ T', 'ARTYX&-T7', 567, 543, 'AEWR-075RJ']
    

    在线代码解释如下:

    l=[]
    for i in List:
        if isinstance(i, str):
            l.append(i.upper())
        else:
            l.append(i)
    

    输出:

    ['A34_RTXF $ T', 'ARTYX&-T7', 567, 543, 'AEWR-075RJ']
    

    【讨论】:

      【解决方案2】:

      U 可以遍历列表并检查当前元素是否为字符串或整数。如果是字符串:加上 .upper()。如果是整数:直接添加到列表中。

      List=["A34_rtXf $ t", "Artyx&-T7", 567, 543,"Aewr-075rJ"]
      
      new_list = []
      for element in List:
          if isinstance(element, str):
              new_list.append(element.upper())
              print(element.upper())
          else:
              new_list.append(element)
      

      输出:

      print(new_list)
      ['A34_RTXF $ T', 'ARTYX&-T7', 567, 543, 'AEWR-075RJ']
      

      【讨论】:

        【解决方案3】:
        words = ["A34_rtXf $ t", "Artyx&-T7", 567, 543,"Aewr-075rJ"]
        new_words = list()
        
        for word in words:
            if type(word) is str:
                new_word = ""
                for char in word:
                    if type(char) is str:
                        new_char = char.upper()
                        new_word += new_char
                    else:
                        new_word += char
                new_words.append(new_word)
            else:
                new_words.append(word)
            
        print(new_words)
        

        输出:

        ['A34_RTXF $ T', 'ARTYX&-T7', 567, 543, 'AEWR-075RJ']
        

        【讨论】:

          【解决方案4】:

          您可以定义一个 lambda 函数来匹配您想要的内容 - 只制作大写字符串元素 - 然后使用 map 将其应用到您的列表中。

          >>> List=["A34_rtXf $ t", "Artyx&-T7", 567, 543,"Aewr-075rJ"]
          >>> f = lambda e: e.upper() if isinstance(e, str) else e
          >>> list(map(f, List))
          ['A34_RTXF $ T', 'ARTYX&-T7', 567, 543, 'AEWR-075RJ']
          

          【讨论】:

            猜你喜欢
            • 2013-02-04
            • 2012-02-06
            • 1970-01-01
            • 2019-12-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-04-17
            • 1970-01-01
            相关资源
            最近更新 更多