Formatting while using "=" syntax in f-string python - python

If there is a variable var=0.00012646547, and it is being printed using the "=" syntax feature provided by f-string as
print(f'{var=}')
, is there a way to format the output which would provide a similar result as the following code ?
print('var\t=\t{0:.3e}'.format(var))
Naturally print(f'{var\t=%.3e}') doesnot work as it is messing with the f-string syntax

You are probably looking for this: print(f'var\t=\t{var:.3e}')
This will print out the value of var in scientific notation with three digits following the decimal point. \t is for inserting tabs for formatting.

Related

How to add a string inside an f-string while formatting it in Python?

I was padding an output in a print statement with a simple code which uses .format() function
print('{:-<100}'.format('xyz'))
I was able to get a similar output using f-strings by creating a new variable
library = 'xyz'
print(f'{library:-<100}')
Question: Is there a way to add the string 'xyz' inside the f-string without having to create a new variable?
I tried the code below, but it gave me an error:
print(f'xyz:-<100')
If I understand your question right, then:
You can just use double-qouted string inside single-quoted f-string
print(f'{"xyz":-<100}')
and optional without f-string and format
print("xyz".ljust(100, "-"))
If I'm not mistaken, what you want to do is:
print(f"{'xyz':-<100}") # You can use expressions here, not only variables!
PS: Regarding the error, are you sure you are running Python +3.6?
Yes, there is a way to add the string ('xyz') inside the fstring without having to create a new variable.
Just add the string 'xyz' outside of the curly brackets '{}'
Example:
print(f'xyz{:-<100}')

How to handle formatting a regular string which could be a f-string [C0209]

For the following line:
print("{0: <24}".format("==> core=") + str(my_dict["core"]))
I am getting following warning message:
[consider-using-f-string] Formatting a regular string which could be a f-string [C0209]
Could I reformat it using f-string?
You could change the code to print(f"{'==> core=': <24}{my_dict['core']}"). The cast to string is implicit.
In your case, the refactoring would look like this:
print(f"{'==> core=': <24}" + str(my_dict['core']))
Basically, instead of "{0:...}".format(bar) you write f"{bar:...}". (Note, you have to use single quotes inside of your f-string, since double quotes would terminate the string too early.)
Check out https://realpython.com/python-f-strings/ for a nice introduction to f-strings.

f-string formula inside curly brackets not working

I am on Python 3.7.
My code on line 3 works fine, however when I insert the underlying formula into line 4, my code returns the error:
SyntaxError: f-string: mismatched '(', '{', or '['
(the error points to the first '(' in line 4.
My code is:
cheapest_plan_point = 3122.54
phrase = format(round(cheapest_plan_point), ",")
print(f"1: {phrase}")
print(f"2: {format(round(cheapest_plan_point), ",")}")
I can't figure out what is wrong with line 4.
You used " quotes inside a "..." delimited string.
Python sees:
print(f"2: {format(round(cheapest_plan_point), "
,
")}")
so the )} is a new, separate string.
Use different delimiters:
print(f"2: {format(round(cheapest_plan_point), ',')}")
However, you don't need to use format() here. In an f-string, you already are formatting each interpolated value! Just add :, to apply the formatting instruction directly to the round() result:
print(f"2: {round(cheapest_plan_point):,}")
The format {expression:formatting_spec} applies formatting_spec to the outcome of expression, just as if you used {format(expression, 'formatting_spec')}, but without having to call format() and without having to put the formatting_spec part in quotes.

Printing subscript in python

In Python 3.3, is there any way to make a part of text in a string subscript when printed?
e.g. H₂ (H and then a subscript 2)
If all you care about are digits, you can use the str.maketrans() and str.translate() methods:
example_string = "A0B1C2D3E4F5G6H7I8J9"
SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
SUP = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
print(example_string.translate(SUP))
print(example_string.translate(SUB))
Which will output:
A⁰B¹C²D³E⁴F⁵G⁶H⁷I⁸J⁹
A₀B₁C₂D₃E₄F₅G₆H₇I₈J₉
Note that this won't work in Python 2 - see Python 2 maketrans() function doesn't work with Unicode for an explanation of why that's the case, and how to work around it.
The output performed on the console is simple text. If the terminal supports unicode (most do nowadays) you can use unicode's subscripts. (e.g H₂) Namely the subscripts are in the ranges:
0x208N for numbers, +, -, =, (, ) (N goes from 0 to F)
0x209N for letters
For example:
In [6]: print(u'H\u2082O\u2082')
H₂O₂
For more complex output you must use a markup language (e.g. HTML) or a typesetting language (e.g. LaTeX).
Using code like this works too:
print('\N{GREEK SMALL LETTER PI}r\N{SUPERSCRIPT TWO}')
print('\N{GREEK CAPITAL LETTER THETA}r\N{SUBSCRIPT TWO}')
The output being:
πr²
Θ₂
Note that this works on Python versions 3.3 and higher only. Unicode formatting.
If you want to use it on the axes of a plot you can do:
import matplotlib.pyplot as plt
plt.plot([1])
plt.ylabel(r'$H_{2}$')
plt.show()
which gives
By using this code you can use alphabets on the superscript and subscript
In This code
format() is Function and in Format function ('\unicode')
By using this table (Unicode subscripts and superscripts on Wikipedia) you can give suitable unicode to the suitable one
you can use superscript and sub script
"10{}".format('\u00B2') # superscript 2

How can I print a string using .format(), and print literal curly brackets around my replaced string [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I print a literal “{}” characters in python string and also use .format on it?
Basically, I want to use .format(), like this:
my_string = '{{0}:{1}}'.format('hello', 'bonjour')
And have it match:
my_string = '{hello:bonjour}' #this is a string with literal curly brackets
However, the first piece of code gives me an error.
The curly brackets are important, because I'm using Python to communicate with a piece of software via text-based commands. I have no control over what kind of formatting the fosoftware expects, so it's crucial that I sort out all the formatting on my end. It uses curly brackets around strings to ensure that spaces in the strings are interpreted as single strings, rather than multiple arguments — much like you normally do with quotation marks in file paths, for example.
I'm currently using the older method:
my_string = '{%s:%s}' % ('hello', 'bonjour')
Which certainly works, but .format() seems easier to read, and when I'm sending commands with five or more variables all in one string, then readability becomes a significant issue.
Thanks!
Here is the new style:
>>> '{{{0}:{1}}}'.format('hello', 'bonjour')
'{hello:bonjour}'
But I thinking escaping is somewhat hard to read, so I prefer to switch back to the older style to avoid escaping:
>>> '{%s:%s}' % ('hello', 'bonjour')
'{hello:bonjour}'

Categories