Aligning output in Python? - python

Is there a way where I can right-align my output in such a way like this:
Item: $ 13.69
Tax: $ 5.30
Oth: $ 2.50
---------------
Total: $ 99.80
Please note that I am using Python 3.

You can use the .format method of strings to do this:
fmt = '{0:>5}: ${1:>6.2f}'
print(fmt.format('Item', 13.69)) # Prints ' Item: $ 13.69'
print(fmt.format('Tax', 5.3))
print(fmt.format('Oth', 2.5))
print('-'*len(fmt.format('Item', 13.69))) # Prints as many '-' as the length of the printed strings
print(fmt.format('Total', 99.8))
# etc...
The '{0:>5}' part is saying "take the zeroth item given to .format, and right justify it within 5 spaces". The '{1:>6.2f}' part is saying take the first item given to .format, right justify it within 6 spaces, formatting as a decimal with 2 decimal places.
Of course, in real code this would likely be part of a loop.

Use string formatting:
print("$%6s" % dec_or_string)

You can use the same amount of spaces before the text with all of the items you want to align.
Another option would be to use the str.format operator as explained here.

Related

Add spaces at the beginning of the print output in python

I'm wondering how Am I suppose to add 4 spaces at the beginnings of the print outputs with f-string or format in python?
This is what I use to print now:
print('{:<10}'.format('Constant'),'{:{width}.{prec}f}'.format(122, width=10, prec=3))
and my output look like this:
Constant 122.000
but what I want is to have 4 spaces before the constant in the output like:
( 4 spaces here )Constant 122.000
Any ideas? Thanks a lot!
You can use ' ' + string (as suggested), but a more robust approach could be:
string="Test String leading space to be added"
spaces_to_add = 4
string_length=len(string) + spaces_to_add # will be adding 4 extra spaces
string_revised=string.rjust(string_length)
result:
' Test String leading space to be added'
There's a couple ways you could do it:
If Constant is really an unchanging constant, why not just
print(f" {Constant}", ...)
before your other string?
With your current implementation, you are left-aligning to a width of 10 characters. If you swap that to right-align, like '{:>12}'.format('Constant') ("Constant" is 8 characters, 12 - 8 = 4 spaces) It will put 4 characters in front of the string.
Here's a Python f-string syntax cheat sheet I've used before:
https://myshell.co.uk/blog/2018/11/python-f-string-formatting-cheatsheet/
And the official docs: PEP 3101

How would I print all the instances when the "$" shows up?

I have this string and I'm basically trying to get the numbers after the "$" shows up. For example, I would want an output like:
>>> 100, 654, 123, 111.654
The variable and string:
file = """| $100 on the first line
| $654 on the second line
| $123 on the third line
| $111.654 on the fourth line"""
And as of right now, I have this bit of code that I think helps me separate the numbers. But I can't figure out why it's only separating the fourth line. It only prints out 111.654
txt = io.StringIO(file).getvalue()
idx = txt.rfind('$')
print(txt[idx+1:].split()[0])
Is there an easier way to do this or am I just forgetting something?
Your code finds only the last $ because that's exactly what you programmed it to do.
You take the entire input, find the last $, and then split the rest of the string. This specifically ignores any other $ in the input.
You cite "line" as if it's a unit of your program, but you've done nothing to iterate through lines. I recommend that you quit fiddling with io and simply use standard file operations. You find this in any tutorial on Python files.
In the meantime, here's how you handle the input you have:
by_lines = txt.split('\n') # Split in newline characters
for line in by_lines:
idx = line.rfind('$')
print(line[idx+1:].split()[0])
Output:
100
654
123
111.654
Does that get you moving?
Regular expressions yay:
import re
matches = re.findall(r'\$(\d+\.\d+|\d+)', file)
Finds all integer and float amounts, ensures trailing '.' fullstops are not incorrectly captured.
This should do it! For every character in txt: if it is '$' then continue until you find a space.
print(*[txt[i+1: i + txt[i:].find(' ')] for i in range(0, len(txt)) if txt[i]=='$'])
Output:
100 654 123 111.654
Your whole sequence appears to be a single string. Try using the split function to break it into separate lines. Then, I believe you need to iterate through the entire list, searching for $ at each iteration.
I'm not the most fluent in python, but maybe something like this:
for i in txt.split('\n'):
idx=txt.rfind('$')
print(txt[idx+1].split()[0])
How about this?
re.findall('\$(\d+\.?\d*)', file)
# ['100', '654', '123', '111.654']
The regex looks for the dollar sign \$ then grabs the maximum sized group available () containing one or more digits \d+ and zero or one decimal points \.? and zero or more digits \d* after that.

Using commas in dollar values in a printed table

I'm printing a table - several rows containing various variable types -
example:
print('{:10s} ${:12.0f} {:10.1f}%'.format(ID,value,change))
first $324681 2.4%
where the integers 10, 12, and 10 provide the column spacing I want.
But I want to have the $ amounts printed with a comma separator, thus:
print('{:10s} ${:,.0f} {:10.1f}%'.format(ID,value,change))
first $324,681 2.4%
But this loses the '12' spaces allowed for the second item.
But when I try
print('{:10s} ${:,12.0f} {:10.1f}%'.format(ID,value,change))
I get "ValueError: Invalid format specifier"
How can I get both the commas and control over the column spacing?
Python 3.6 running in Spyder.
This should do the trick:
print('{:10s} ${:1,d} {:10.1f}%'.format('first', 324681, 2.4))
OUTPUT:
first $324,681 2.4%
If you are content to have the specified total width but the dollar in a fixed column possibly separated from the digits, then you could just do what you were doing, but with the 12 before the ,.
>>> value = 324681
>>> ID = "first"
>>> change = 2.4
>>> print('{:10s} ${:12,.0f} {:10.1f}%'.format(ID,value,change))
first $ 324,681 2.4%
If you want the numbers to follow immediately after the $, then you can format it as a string without any padding, and then use the string in a fixed-width format specifier:
>>> print('{:10s} {:13s} {:10.1f}%'.format(ID ,'${:,.0f}'.format(value), change))
first $324,681 2.4%
or:
>>> print('{:10s} {:>13s} {:10.1f}%'.format(ID ,'${:,.0f}'.format(value), change))
first $324,681 2.4%
(The width specifier is increased to 13 here, because the $ sign itself is in addition to the 12 characters used for the number.)

How to attach a string to an integer in Python 3

I've got a two letter word that I'd like to attach to a double digit number. The word is an integer and the number is a string.
Say the name of the number is "number" and the name of the word is "word".
How would you make it print both of them together without spaces. When I try it right now it still has a space between them regardless of what I try.
Thanks !
'{}{}'.format(word, number)
For example,
In [19]: word='XY'
In [20]: number=123
In [21]: print('{}{}'.format(word, number))
XY123
The print function has a sep parameter that controls spacing between items:
print(number, word, sep="")
If you need a string, rather than printing, than unutbu's answer with string formatting is better, but this may get you to your desired results with fewer steps.
In python 3 the preferred way to construct strings is by using format
To print out a word and a number joined together you would use:
print("{}{}".format(word, number))

How to store number from string in python

i have string like this:
string = "The stock item "28031 (111111: Test product)" was added successfully."
I need store from string the first 5 numbers ( for example "28031" ) and save them to another string.
It's because i am selenium tester and every time i am create new stock item he has different first 5 numbers.
Thank you for your help
Filip
m = re.search("\d+", string)
print m.group(0)
prints 28031
It just selects the first group of digits, regardless of the length (2803 would be selected, too)
Firstly I am assuming all these strings have exactly the same format. If so the simplest way to get your stock item number is:
stocknumber = string.split()[3][1:]
After sehe answer I leave mine edited just to show how to match 5 digits
import re
re.search('\d{5}', string).group(0)
EDIT : neurino solution is the smartest!! use it
EDIT : sehe solution is smart and perfect you can add this line to get only the first 5 numbers:
print m.group(0)[0:5]
using [0:5] means to take string elements from 0 to 5 (first 5 elements)
use the str.isdigit built-in function
string = "The stock item 28031 "
Digitstring=''
for i in string:
if i.isdigit():
Digitstring+=i
print Digitstring
Output:
28031
you can count to first x numbers you need and then stop.

Categories

Resources