Print list without brackets in a single row

前端 未结 12 1138
北恋
北恋 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:39

    For array of integer type, we need to change it to string type first and than use join function to get clean output without brackets.

        arr = [1, 2, 3, 4, 5]    
        print(', '.join(map(str, arr)))
    

    OUTPUT - 1, 2, 3, 4, 5

    For array of string type, we need to use join function directly to get clean output without brackets.

        arr = ["Ram", "Mohan", "Shyam", "Dilip", "Sohan"]
        print(', '.join(arr)
    

    OUTPUT - Ram, Mohan, Shyam, Dilip, Sohan

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

    There are two answers , First is use 'sep' setting

    >>> print(*names, sep = ', ')
    

    The other is below

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

    The following function will take in a list and return a string of the lists' items. This can then be used for logging or printing purposes.

    def listToString(inList):
        outString = ''
        if len(inList)==1:
            outString = outString+str(inList[0])
        if len(inList)>1:
            outString = outString+str(inList[0])
            for items in inList[1:]:
                outString = outString+', '+str(items)
        return outString
    
    0 讨论(0)
  • 2020-11-22 17:50

    If the input array is Integer type then you need to first convert array into string type array and then use join method for joining with , or space whatever you want. e.g:

    >>> arr = [1, 2, 4, 3]
    >>> print(", " . join(arr))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: sequence item 0: expected string, int found
    >>> sarr = [str(a) for a in arr]
    >>> print(", " . join(sarr))
    1, 2, 4, 3
    >>>
    

    Direct using of join which will join the integer and string will throw error as show above.

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

    You need to loop through the list and use end=" "to keep it on one line

    names = ["Sam", "Peter", "James", "Julian", "Ann"]
        index=0
        for name in names:
            print(names[index], end=", ")
            index += 1
    
    0 讨论(0)
  • 2020-11-22 17:52

    Here is a simple one.

    names = ["Sam", "Peter", "James", "Julian", "Ann"]
    print(*names, sep=", ")
    

    the star unpacks the list and return every element in the list.

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