Print list without brackets in a single row

前端 未结 12 1351
北恋
北恋 2020-11-22 17:01

I have a list in Python e.g.

names = [\"Sam\", \"Peter\", \"James\", \"Julian\", \"Ann\"]

I want to print the array in a single line withou

12条回答
  •  一个人的身影
    2020-11-22 18:02

    ','.join(list) will work only if all the items in the list are strings. If you are looking to convert a list of numbers to a comma separated string. such as a = [1, 2, 3, 4] into '1,2,3,4' then you can either

    str(a)[1:-1] # '1, 2, 3, 4'
    

    or

    str(a).lstrip('[').rstrip(']') # '1, 2, 3, 4'
    

    although this won't remove any nested list.

    To convert it back to a list

    a = '1,2,3,4'
    import ast
    ast.literal_eval('['+a+']')
    #[1, 2, 3, 4]
    

提交回复
热议问题