Print list without brackets in a single row

前端 未结 12 1155
北恋
北恋 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 17:55

    I don't know if this is efficient as others but simple logic always works:

    import sys
    name = ["Sam", "Peter", "James", "Julian", "Ann"]
    for i in range(0, len(names)):
        sys.stdout.write(names[i])
        if i != len(names)-1:
            sys.stdout.write(", ")
    

    Output:

    Sam, Peter, James, Julian, Ann

    0 讨论(0)
  • 2020-11-22 17:57
    print(', '.join(names))
    

    This, like it sounds, just takes all the elements of the list and joins them with ', '.

    0 讨论(0)
  • 2020-11-22 17:58

    print(*names)

    this will work in python 3 if you want them to be printed out as space separated. If you need comma or anything else in between go ahead with .join() solution

    0 讨论(0)
  • 2020-11-22 18:00

    This is what you need

    ", ".join(names)
    
    0 讨论(0)
  • 2020-11-22 18:01

    General solution, works on arrays of non-strings:

    >>> print str(names)[1:-1]
    'Sam', 'Peter', 'James', 'Julian', 'Ann'
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
提交回复
热议问题