【问题标题】:Add an exclamation mark at the end of strings in a List在列表中的字符串末尾添加感叹号
【发布时间】:2020-04-06 13:49:38
【问题描述】:

所以我有一个 Python 中的字符串列表

List=["Hello there", "Nice one"]

我想补充!在字符串的末尾,所以它变成了这样

List=["Hello there!", "Nice one!"]

我想我可以迭代使用 split() 将它们变成单独的数组,然后 append("!") 然后加入这是我目前所拥有的。

List=["Hello there", "Nice one"]
for i in List:
    List[i].split()
    List[i].append("!")
    List[i].join()
    print(List(i))

有人可以告诉我更好的方法或帮助我解决这个问题

【问题讨论】:

    标签: python arrays input


    【解决方案1】:

    使用列表理解

    [e+"!" for e in List] 
    

    【讨论】:

      【解决方案2】:

      一种方式可以是这样的:

      >>> List=["Hello there", "Nice one"]
      >>> List_new = [i + '!' for i in List]
      >>> List_new
      ['Hello there!', 'Nice one!']
      

      【讨论】:

        【解决方案3】:

        使用列表推导和连接方法。并强烈建议您不要将list 称为“列表”

        In [1]: data = ["Hello there", "Nice one"]                                      
        
        In [2]: data2 = [''.join([t, '!']) for t in data]                               
        
        In [3]: data2                                                                   
        Out[3]: ['Hello there!', 'Nice one!']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多