hi
in the below code:
# normal pyramid
print("\nNormal Pyramid")
for i in range(5):
x="* "
x=x*i
print(f'{x:^10}')
what is
^10 in last print line?also
{x:<10} and
{x:>10} can be used. what are they?
thanks
the ":^10" in an f-string will center value of 'x' in a 10 character field.
< will left justify. > right justify, ^ center justify
print('0123456789')
value = "Hi"
print(f"{value}")
print(f"{value:<10}")
print(f"{value:>10}")
print(f"{value:^10}")
Output:
0123456789
Hi
Hi
Hi
Hi
You don't often see "<" used.
hi
what does
!r do in below code?
fpath = "C:\new\text\sample.txt"
print(f'this is a test and {fpath}')
# output: this is a test and C:
# ew ext\sample.txt
print(f'this is a test and {fpath!r}')
# out: this is a test and 'C:\new\text\\sample.txt'
fpath = r"C:\new\text\sample.txt"
print(f'this is a test and {fpath}')
# output: this is a test and C:\new\text\sample.txt
print(f'this is a test and {fpath!r}')
# output: this is a test and 'C:\\new\\text\\sample.txt'
thanks
(Nov-07-2023, 08:51 AM)perfringo Wrote: [ -> ]It's always a good idea to read documentation: Format String Syntax and Format Specification Mini-Language
Quote:Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().
hi
I knew that I must explore for f-string, but I did not know where( in which internet address) I must search.
can you tell me where I must search when I encounter an ambiguous subject?
thanks
Search is very wide subject and "how" depends on very many factors.
For Python I personally follow this pattern:
1 Search Python built-in help
2. Search Python documentation at python.org
3. Search internet with Google
This specific subject was about string formatting so following should be pretty self-explanatory:
>>> help('format')
Help on built-in function format in module builtins:
format(value, format_spec='', /)
Return value.__format__(format_spec)
format_spec defaults to the empty string.
See the Format Specification Mini-Language section of help('FORMATTING') for
details.
>>> # very helpful hint what to search
>>> help('FORMATTING')
# oh boy, this will spill out lengthy and quite comprehensive information