简体   繁体   中英

Suppress print newline in python 3 str.format

I am using Python 3 and am trying to use my print statements with the str.format.

eg:

print ('{0:3d} {1:6d} {2:10s} '.format (count1,count2,string1)) 

When I try to use the end='' to suppress the subsequent newline, this is ignored. A newline always happens.

How do I suppress the subsequent newline?

Source:

int1= 1
int2 = 999
string1 = 'qwerty'
print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1))
print ('newline')
print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1,end=''))
print ('newline')
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "copyright", "credits" or "license()" for more information.

1 999 qwerty
newline

1 999 qwerty
newline

Your problem is that you have the end='' argument being passed to the format function, not to the print function.

Change this line:

print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1,end=''))

To this:

print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1), end='')

By the way, you should also give PEP8 a read. It defines standards for Python coding styles, that you really should try to follow, unless you're working with a group of people that have agreed on some other style standards. In particular, your spacing is a bit weird around function calls - you shouldn't have spaces between function names and the argument parentheses, or between the parentheses and the first argument. I wrote my suggested solution to your problem in a way that maintains your current style, but it really should look more like this:

print('{0:3d} {1:6d} {2:10s} '.format(int1, int2, string1), end='')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM