Need Help on String Formatting - python

I've written this program in Python 3 that takes a CSV file that finds the min and max death rates for particular states.
I've basically finished the program and it outputs correctly in the shell, but I have a problem:
Different states have different lengths of characters in their names and the spacing does come out correctly, how do I use string formatting to make the strings space evenly regardless of the number of characters printed?
Here is what I have:
print ("\n", "Indicator |", "Min ",
" | Max ")
print ("-----------------------------------------------------------------------------------------------")
This is the output:
It works well for "Minnesota" but for "District of Columbia" it doesn't format evenly.
Any suggestions? Thanks.

Use string formatting as described here: http://docs.python.org/release/3.1.5/library/string.html
e.g.:
print('{:20} | {:20} {:5.2f} | {:20} {:5.2f}'.format(title, states[statemin], minimum, states[statemax], maximum))
Replace 20 with the longest string that will ever occur.
Note that I am assuming that minimum and maximum are floats, if they are strings, you cannot use '{:x.yf}' notation and you could just use {:6} or something like that instead.
{:20} means that 20 characters of space is used for the string, even if it is shorter (it does not truncate when longer). {:5.2f} means that 5 spaces are used for the float, of which 2 are after the decimal point.

Related

How to convert to Python 3

I am in the process of converting Python 2 code into Python 3. Currently I am facing difficulty in converting the following code to Python 3. Please help.
print 'Data cache hit ratio: %4.2f%%' % ratio
Also, what %4.2f%% means?
Tried to rewrite the code with format().
Just put parens around the parameters.
print('Data cache hit ratio: %4.2f%%' % ratio)
There are fancier ways of doing formatting in Python 3, but that will work.
%4.2f says "display this floating point number in a 4-character field with a decimal point and two places after. So, like "9.99". %% says "display a percent sign". The formatting here is straight from the C printf function.
f denotes the fixed point notation. The value that precedes with % (4.2) is for denoting the width (4) and the precision (2) of the number respectively.
You can use either .format or f string
print("Floating point {0:4.2f}".format(ratio))
print(f' Floating point {ratio:4.2f}')
Here 4 is the total width of the field being printed, lefted-padded by spaces. 2 is the number of digits after the decimal point. You can read more about it here https://docs.python.org/3/library/string.html#format-specification-mini-language

Remove decimals from a Float column

shocked beyond belief how difficult this is turning out to be. All I can find are suggestions to change the format of the column to 'int' but I need to keep the comma thousand separators and changing the format to int gets rid of them. THEN i can't find anything on how to add comma separators to an int column. any ideas? really is nothing for me to share in addition to above in terms of what i've tried.
Format your floats...in a string format?
my_string = '{:,.0f}'. format(my_number)
E.g.:
x = 1000.00
'{:,.0f}'. format(x)-> 1,000
Which gives you what you want...something you can print with commas. 0f sets to 0 precision. (for how many decimal places)

python syntax for formatting integer

I am new in python. In the following line
'{0:6}{1:02d}'.format(date, hour)
I figured out that hour should be 0 filled to two digits. But I can't figure out what it is formatting date to be. afaik, both date and hour are int values here.
{0:6} is just going to take the 0th argument (date) and print it with a minimum of 6 characters. It can be an integer, a string, ... Nothing else special there. It is a guess at what format was intended for date (ie. May1st, 5/1, ...)
You are correct about the interpretation of the {1:02d} which is the hour field print in a minimum of 2 decimal digits with 0's to pad.
Try it and see:
a = 10
b = 6
print('{0:6}{1:02}'.format(a, b))
#output => ' 1006'
So like 02 adds "0"s to the variable until it is of 2 length. Just adding a number (6) will add spaces to the front until the variable length is 6.
Python's Common String Operator's Docs has more.

removing a % sign and parsing result as an integer

I am scraping an XML file and returning a load of percentages, pulled out directly as a percentage sometimes negative with the % sign already attached e.g.
-38%
-2%
4%
25%
I am trying to do a filter such as this:
if percentage < 20.0 : continue;
However I cannot perform this filter, I assume as a result of the % symbol.
For reference I use:
cell['roi']
To get the percentages, iterating through each row using:
for row in xmlload1['rows']:
cell = row["cell"]
How do I get around this % symbol? Is there an easy way?
You can't perform that filter because you're trying to compare a string (like "4%") to a float (20.0). In Python 3, this will raise a TypeError; in Python 2, it will "work", but all strings will be treated as greater than the number 20.0, so it won't do any good.
You need to convert the string to a float before you can use it as a float. But you don't want to convert the whole string, just the part before the "%" character. (Because 4% isn't a number, it's only the 4 that's a number.)
So, let's do it in two steps: use rstrip to remove the "%", then use float to convert it to a float.
cell = float(row["cell"].rstrip("%"))
You can pass a string to strip which will strip the characters passed in the passed string, the below will strip %, newlines and spaces:
cell = int(row["cell"].strip("%\n "))

Python, string , integer

I have a string variable:
str1 = '0000120000210000'
I want to convert the string into an integer without losing the first 4 zero characters. In other words, I want the integer variable to also store the first 4 zero digits as part of the integer.
I tried the int() function, but I'm not able to retain the first four digits.
You can use two integers, one to store the width of the number, and the other to store the number itself:
kw = len(s)
k = int(s)
To put the number back together in a string, use format:
print '{:0{width}}'.format(k, width=kw) # prints 0000120000210000
But, in general, you should not store identifiers (such as credit card numbers, student IDs, etc.) as integers, even if they appear to be. Numbers in these contexts should only be used if you need to do arithmetic, and you don't usually do arithmetic with identifiers.
What you want simply cannot be done.. Integer value does not store the leading zero's, because there can be any number of them. So, it can't be said how many to store.
But if you want to print it like that, that can be done by formatting output.
EDIT: -
Added #TimPietzcker's comment from OP to make complete answer: -
You should never store a number as an integer unless you're planning on doing arithmetic with it. In all other cases, they should be stored as strings

Categories

Resources