Python - Unwanted whitespace in numeric output

Hi,

In the following print() statement:

 print "Your pace was;", minutes_per_mile , ":", seconds_per_mile, "per mile."

Open in new window


the output of the two integers is:

Your pace was; 8 : 34 per mile.

Open in new window


Each int field seems to be outputted with a leading and a trailing pace. How can I remove?

Thanks,
Steve
LVL 4
Stephen KairysTechnical Writer - ConsultantAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michael FowlerSolutions ConsultantCommented:
Try the .strip() function

print "Your pace was;", minutes_per_mile.strip() , ":", seconds_per_mile.strip(), "per mile."

Open in new window

Stephen KairysTechnical Writer - ConsultantAuthor Commented:
So does strip() work for all basic datatypes? (e.g. float, integer, string)?
Thanks.
Michael FowlerSolutions ConsultantCommented:
The function works with string datatypes
https://docs.python.org/2/library/string.html

Given that your values are returning with whitespace I assumed that they are strings.

For other datatypes you can cast to string using str(x) eg
print "Your pace was;", str(minutes_per_mile).strip() , ":", str(seconds_per_mile).strip(), "per mile."

Open in new window

Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Stephen KairysTechnical Writer - ConsultantAuthor Commented:
Michael,
I'll try the above tomorrow. Thank you!

Steve
Michael FowlerSolutions ConsultantCommented:
Hi Steve

Been a while since I have done any python and so I did some testing. The correct answer for your issue is to use string concatenation because when you print a list of strings whitespace is automatically added between the values. So a working answer is

print "Your pace was; " + str(minutes_per_mile) + ":" + str(seconds_per_mile) + " per mile."

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
clockwatcherCommented:
Strip is a method of a string.  If your variables actually hold floats or integers, that code would have thrown an exception:
>>> x = 3.3
>>> x.strip()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'strip'
>>> y = 5
>>> y.strip()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'strip'

Open in new window


But even had your variables been strings and that code not thrown an exception, it still would have given you white space:
>>> x = "3"
>>> print "hello",x,"there"
hello 3 there

Open in new window


The reason that you're getting whitespace is because you're using the "," as a separator.  Python 2 will interpret that to mean that you're trying to print out two separate items and will separate them for you.
>>> print "hello","there"
hello there

Open in new window


In your case, you're not really trying to print out 3 separate items.  You're trying to print out a single concatenated string.  So you can either concatenate the string,
 print "Your pace was;" + str(minutes_per_mile) + ":" + str(seconds_per_mile) + " per mile."

Open in new window


Or more typically you can use a string formatter.  Basically, a templated string replacement.
print "Your pace was {mpm}.{spm} per mile".format(mpm=minutes_per_mile, spm=seconds_per_mile)

Open in new window


The items in curly brackets become named parameters to the string's format method.   See the following site for example of using python's string formatting functions: https://pyformat.info/
peprCommented:
To add to clockwatcher's good comment, adding the space between the arguments is a normal, documented feature. In Python 3, the print command was converted to the print() function, and it takes an optional argument that allows you to set the separator (space by default):
>>> print("Your pace was;", 5, ":", 35, "per mile.", sep='')
Your pace was;5:35per mile.

Open in new window

But this is not what you really need. The usual way to solve that problem is to use string format  -- as clockwather suggested. If you use the older Python 2 that did not know the .format(), you can use the older way
>>> print "Your pace was; %d:%d per mile." % (5, 35)
Your pace was; 5:35 per mile.

Open in new window

If your Python 2 is new enough, you can also simplify the placeholders for the values:
>>> print "Your pace was; {}:{} per mile.".format(5, 35)
Your pace was; 5:35 per mile.

Open in new window

Stephen KairysTechnical Writer - ConsultantAuthor Commented:
All,

This is great info. I tried the str concatenating method with good results.

Now is there a command line switch for PYTHON (e.g. PYTHON -VER) that will show me the version#? I want to play around with the string formatting.

Thanks.
peprCommented:
python --version

Open in new window


Or if you enter the iteractive mode, you can simly read the top lines.

If you use Windows and Python 3.3+, then you probably want to use The Python Launcher for Windows (installed automatically from the official distribution). Then you probably do not have your python.exe in PATH (and you do not want to have it in PATH). In the case, you launch Python via py:
py --version

Open in new window

If the version is not said explicitly, then the highest Python 2.x is launched.

py -3 --version

Open in new window

This launches the highest Python 3 version.

If you want to test the version from the code, you can import the sys module for the purpose:
>>> import sys
>>> sys.version
'2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]'
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=10, releaselevel='final', serial=0)
>>> sys.version_info.major
2
>>> sys.version_info.minor
7
>>> sys.version_info.micro
10

Open in new window

Stephen KairysTechnical Writer - ConsultantAuthor Commented:
@Pepr
Version is 2.7.9

>>>
If your Python 2 is new enough, you can also simplify the placeholders for the values:
print "Your pace was; {}:{} per mile.".format(5, 35)
Your pace was; 5:35 per mile.

Open in new window

<<<

So is 2.7.9 recent enough for the above? Thanks.
peprCommented:
Yes. See https://docs.python.org/2/library/string.html#format-string-syntax . The feature was introduced in Python 2.7.

I understand that you may be afraid to try, but you should try it anyway ;) Use the interactive Python mode. Launch the cmd first and type python without arguments. The >>> in my examples is the prompt that is shown in the interactive mode. What follows it a text that was typed (or can be copy/pasted). After pressing Enter, the line without the prompt shows the reaction (the result of the command).

If you learn Python, and if you , I suggest to start wi
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
Hi Pepr. I think your post has been truncated...plz see above. :) Thanks. And yes, I'll try interactive mode when I get a moment.
peprCommented:
... and if you are not forced to use Python 2, you should start with Python 3.

(It was my fault ;)
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
Thank you all!!

I ended up going with Pepr's idea:

print "Your pace was; %d:%d per mile." % (5, 35)

but changed to
print "Your pace was; %2d:%02d per mile." % (5, 35)

otherwise, a pace, of, say, 8:07 would display as 8:7
:)

NOTE: I did not try every possible solution presented, so anyone using the info in this thread should try for themselves before implementing. :)

As usual, I'm proud to be part of the EE community. Have a good weekend, everyone!

Steve
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.