Python concatenate string & list

前端 未结 5 1905
清酒与你
清酒与你 2020-12-14 08:08

I have a list and string:

fruits = [\'banana\', \'apple\', \'plum\']
mystr = \'i like the following fruits: \'

How can I concatenate them s

相关标签:
5条回答
  • 2020-12-14 08:29

    The simple code below will work:

    print(mystr, fruits)
    
    0 讨论(0)
  • 2020-12-14 08:30

    You can use this code,

    fruits = ['banana', 'apple', 'plum', 'pineapple', 'cherry']
    mystr = 'i like the following fruits: '
    print (mystr + ', '.join(fruits))
    

    The above code will return the output as below:

    i like the following fruits: banana, apple, plum, pineapple, cherry
    
    0 讨论(0)
  • 2020-12-14 08:31

    You can use str.join.

    result = "i like the following fruits: "+', '.join(fruits)
    

    (assuming fruits only contains strings). If fruits contains a non-string, you can convert it easily by creating a generator expression on the fly:

    ', '.join(str(f) for f in fruits)
    
    0 讨论(0)
  • 2020-12-14 08:35

    Join the list, then add the strings.

    print mystr + ', '.join(fruits)
    

    And don't use the name of a built-in type (str) as a variable name.

    0 讨论(0)
  • 2020-12-14 08:37

    You're going to have a problem if you name your variables the same as Python built-ins. Otherwise this would work:

    s = s + ', '.join([str(fruit) for fruit in fruits])
    
    0 讨论(0)
提交回复
热议问题