How to concatenate items in a list to a single string?

后端 未结 11 1932
北荒
北荒 2020-11-21 05:59

Is there a simpler way to concatenate string items in a list into a single string? Can I use the str.join() function?

E.g. this is the input [\'t

相关标签:
11条回答
  • 2020-11-21 06:19

    We can specify how we have to join the string. Instead of '-', we can use ' '

    sentence = ['this','is','a','sentence']
    s=(" ".join(sentence))
    print(s)
    
    0 讨论(0)
  • 2020-11-21 06:20

    A more generic way to convert python lists to strings would be:

    >>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> my_lst_str = ''.join(map(str, my_lst))
    >>> print(my_lst_str)
    '12345678910'
    
    0 讨论(0)
  • 2020-11-21 06:21
    def eggs(someParameter):
        del spam[3]
        someParameter.insert(3, ' and cats.')
    
    
    spam = ['apples', 'bananas', 'tofu', 'cats']
    eggs(spam)
    spam =(','.join(spam))
    print(spam)
    
    0 讨论(0)
  • 2020-11-21 06:24

    Use join:

    >>> sentence = ['this','is','a','sentence']
    >>> '-'.join(sentence)
    'this-is-a-sentence'
    
    0 讨论(0)
  • 2020-11-21 06:26

    We can also use Python's reduce function:

    from functools import reduce
    
    sentence = ['this','is','a','sentence']
    out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
    print(out_str)
    
    0 讨论(0)
提交回复
热议问题