How to print variables without spaces between values

This question already has an answer here:

  • How to print without newline or space? 26 answers

  • Don't use print ..., if you don't want spaces. Use string concatenation or formatting.

    Concatenation:

    print 'Value is "' + str(value) + '"'
    

    Formatting:

    print 'Value is "{}"'.format(value)
    

    The latter is far more flexible, see the str.format() method documentation and the Formatting String Syntax section.

    You'll also come across the older % formatting style:

    print 'Value is "%d"' % value
    print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)
    

    but this isn't as flexible as the newer str.format() method.


    Just an easy answer for the future which I found easy to use as a starter: Similar to using end='' to avoid a new line, you can use sep='' to avoid the white spaces...for this question here, it would look like this: print('Value is "', value, '"', sep = '')

    May it help someone in the future.


    It's the comma which is providing that extra white space.

    One way is to use the string % method:

    print 'Value is "%d"' % (value)
    

    which is like printf in C, allowing you to incorporate and format the items after % by using format specifiers in the string itself. Another example, showing the use of multiple values:

    print '%s is %3d.%d' % ('pi', 3, 14159)
    

    For what it's worth, Python 3 greatly improves the situation by allowing you to specify the separator and terminator for a single print call:

    >>> print(1,2,3,4,5)
    1 2 3 4 5
    
    >>> print(1,2,3,4,5,end='<<n')
    1 2 3 4 5<<
    
    >>> print(1,2,3,4,5,sep=':',end='<<n')
    1:2:3:4:5<<
    
    链接地址: http://www.djcxy.com/p/77208.html

    上一篇: 如何在同一行上打印2个项目

    下一篇: 如何在值之间没有空格的情况下打印变量