I am trying to print a string with \t at both beginning and end, like below.
name2print="\tabhinav\t"
lastname="gupta"
print(name2print,lastname)
Expected output should be
abhinav gupta
But the actual output is
abhinav gupta
I tried with lstrip like this and as expected strips only the beginning "\t" and prints the trailing "\t"
print(name2print.lstrip(),lastname)
Output:
abhinav gupta
If lstrip() can print the trailing "\t" then why is the print statement ignoring the trailing tab character in the first string while printing? I think I am missing something basic. Please help.
CodePudding user response:
The output is correct. \t
adds a variable number of spaces so that the next printed character is at a position which is a multiple of 8 (or whatever is configured in your terminal).
In your example the first \t
adds 8 spaces, then you print abhinav
(7 characters), the next tab adds 1 space to make it a multiple of 8, then the ,
in your print
statements adds 1 space, then you print gupta
:
a b h i n a v g u p t a
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
└───── \t ────┘ \t, └\t┘
If you always want to print 8 spaces, use " "
.
CodePudding user response:
When you print a tab character, Python uses it to align the string to the end of a 4 character boundary so that the next thing that gets printed is aligned to the next boundary. So you will not always get 4 spaces. Rather, you'll get between 1 and 4 spaces. Here's some code to demonstrate this:
print('\ta\t','bbbb')
print('\taa\t','bbbb')
print('\taaa\t','bbbb')
print('\taaaa\t','bbbb')
print('\taaaaa\t','bbbb')
print('1234567890123456')
Result:
a bbbb
aa bbbb
aaa bbbb
aaaa bbbb
aaaaa bbbb
1234567890123456
The bbbb
values are aligned to the 10th and 14th positions rather than the 9th and 13th because of the extra space character that the Python print()
function adds between terms. The second string being aligned to 4 character boundaries is ' bbbb'
.