I was able to align the numbers by decimal points but I don't know how to add the comma. I know how to add commas using the format() but don't know how to align and add commas together. I need to align by the decimal points and have commas also.
print(f"{i 1}\t\t\t{salary :11.2f}")
This is a line inside the for loop.
CodePudding user response:
This worked for me, if I understood you correctly. Replace the 3 tabs you have with ">25", directly after the colon. The ">" adds space to the left and the text will be aligned to the right. 25 is how many character spaces you're allowing for. 25 was an arbitrary number I picked for this example, it can be anything with enough space to fit your strings and the space desired (like, the longest numbers you have plus your tab spaces). Add the comma after ">25" to print the numbers with commas.
salaries = [10000, 200000, 3000000, 40000000]
for i in range(len(salaries)):
salary = salaries[i]
print_string = f"{i 1}{salary :>25,.2f}"
print(print_string)
CodePudding user response:
Below solution requires administrative permissions.
Step 1: Install German locale.
1.1 Uncomment German locale line in /etc/locale.gen
.
Any text editor can be used. After editing result should look as follows:
grep ^de /etc/locale.gen
de_DE.UTF-8 UTF-8
1.2 Install German locale:
sudo locale-gen en_US.UTF-8 de_DE.UTF-8
sudo update-locale LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8
Step 2. Use German locale. Example:
#!/usr/bin/python3.9
import locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
for i in range(0,10):
salary=10000*i 1000
print('{0:2d}\t\t\t'.format(i 1),end='')
print(locale.format_string('.2f', salary))
Output:
1 1000,00
2 11000,00
3 21000,00
4 31000,00
5 41000,00
6 51000,00
7 61000,00
8 71000,00
9 81000,00
10 91000,00
My environment:
uname -a ; lsb_release -a |& grep -v ^No
Linux LAPTOP-YYYYYYYY 4.4.0-19041-Microsoft #1237-Microsoft Sat Sep 11 14:32:00 PST 2021 x86_64 x86_64 x86_64 GNU/Linux
Distributor ID: Ubuntu
Description: Ubuntu 20.04.3 LTS
Release: 20.04
Codename: focal