Print a list of space-separated elements in Python 3

前端 未结 4 1022
野趣味
野趣味 2020-11-28 04:55

I have a list L of elements, say natural numbers. I want to print them in one line with a single space as a separator. But I don\'t w

4条回答
  •  迷失自我
    2020-11-28 05:33

    You can apply the list as separate arguments:

    print(*L)
    

    and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

    >>> L = [1, 2, 3, 4, 5]
    >>> print(*L)
    1 2 3 4 5
    >>> print(*L, sep=', ')
    1, 2, 3, 4, 5
    >>> print(*L, sep=' -> ')
    1 -> 2 -> 3 -> 4 -> 5
    

    Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

    joined_string = ' '.join([str(v) for v in L])
    print(joined_string)
    # do other things with joined_string
    

    Note that this requires manual conversion to strings for any non-string values in L!

提交回复
热议问题