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.)
Related
Following the Question:
How to set the spaces in a string format in Python 3
Why does the first one work but the second one not?
string='Hello World!'
length = 20
print('{1:>{0}}'.format(length, string))
Results in: Hello World!
string='Hello World!'
length = len(string)
print('{1:>{0}}'.format(length, string))
Results in: Hello World!
Both of your snippets should work fine. The reason why you receive different outputs is that length in your first example is 20, in your second example it is 12 though. As your length is always exactly as long as your string, you will never see additional whitespaces.
In your print statement, the length variable is the total length of the output string. It includes spaces as well as the string.
In the first case, 20 is the total length (8 whitespaces + 12 chars). In the second case, total length is equal to the length of the string. So, it is working in both the cases.
I know that I can use the following to pad leading zeros to a string:
>>> qty = 1
>>> '{:06}'.format(qty)
'000001'
But can I also use the format function to also add thousands separators to get:
'000,001'
I know this can be done by manipulating the text, but can it be achieved with the format() function ?
So i'm trying to work with floats as elements in Python lists but I keep getting this error. I tried making each value a string and then converting it to a float when calling the array to print but that doesn't seem to work either
P1 = [45.100000, ‐65.400000]
print(P1[0])
SyntaxError: invalid character in identifier
Attempt #2
P1 = ["45.100000", "‐65.400000"]
print(float(P1[1]))
ValueError: could not convert string to float: '‐65.400000'
I have a feeling the issues have to do with the negative value in front of the 2nd elements (# index 1)
There is a problem with the hyphen you are using. If you cut and paste the hyphen in your list p1, and check the unicode, it gives:
>>> ord('‐')
8208
Whereas the proper negative or subtraction sign should be:
>>> ord('-')
45
Depending on how you got that list, you either have to figure out why that character got included, or re-type it with the proper Hyphen-Minus
I copied your code and ran it, and all I had to do was replace the "-" Seems like you were using a bad character. Try this;
P1 = [45.100000, -65.400000]
This is because your - is not a minus sign but a hyphen character:
>>> "‐65.400000".encode('utf-8') # copy from your example
b'\xe2\x80\x9065.400000'
>>> "-65.400000".encode('utf-8') # Replace with my minus
b'-65.400000'
\xe2\x80\x90 is a hyphen character, see here: your hyphen is U+2010 and the hyphen-minus is U+002D
How can I automatically place dots by separating it with 3 digits in a group beginning from the right?
Example:
in: 1234; out 1.234
in: 12345678; out 12.345.678
You are looking for a thousands-separator. Format your number with the format() function to using commas as the thousands separator, then replace the commas with dots:
>>> format(1234, ',').replace(',', '.')
'1.234'
>>> format(12345678, ',').replace(',', '.')
'12.345.678'
Here the ',' format signals that the decimal number should be formatted with a thousands-separator (see the Format Specification Mini-language).
The same can be achieved in a wider string format with the str.format() method, where placeholders in the template are replaced with values:
>>> 'Some label for the value: {:,}'.format(1234).replace(',', '.')
'Some label for the value: 1,234'
but then you run the risk of accidentally replacing other full stops in the output string too!
Your other option would be to use the locale-dependent 'n' format, but that requires your machine to be configured for a locale that sets the right LC_NUMERIC options.
Here is a simple solution:
>>> a = 12345678
>>> "{:,}".format(a)
'12,345,678'
>>> "{:,}".format(a).replace(",", ".")
'12.345.678'
>>>
This uses the .format method of a string to add the comma separators and then the .replace method to change those commas to periods.
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.