How can I optimally concat a list of chars to a string?

前端 未结 3 1116
温柔的废话
温柔的废话 2021-01-14 04:56

The data:

list = [\'a\',\'b\',\'x\',\'d\',\'s\']

I want to create a string str = \"abxds\". How can I do that?

Right now I am doing

相关标签:
3条回答
  • 2021-01-14 05:44
    >>> theListOfChars = ['a', 'b', 'x', 'd', 's']
    >>> ''.join(theListOfChars)
    'abxds'
    

    BTW, don't use list or str as variable names as they are names of built-in functions already.

    (Also, there is no char in Python. A "character" is just a string of length 1. So the ''.join method works for list of strings as well.)

    0 讨论(0)
  • 2021-01-14 05:51

    KennyTM's answer is great. Also, if you wanted to make them comma separated or something, it'd be:

    ",".join(characterlist)
    

    This would result in "a,b,x,d,s"

    0 讨论(0)
  • 2021-01-14 05:58

    The thing you're looking for is str.join():

    >>> L = ['a','b','x','d','s']
    >>> ''.join(L)
    'abxds'
    

    (Don't name your variable list, it's a builtin name.)

    0 讨论(0)
提交回复
热议问题