f-string

Why are f-strings faster than str() to parse values?

心已入冬 提交于 2020-01-03 08:28:12
问题 I was playing around with f-strings, (see PEP 498), and I decided to check the speed of the f-string parse, (e.g. f"{1}") in comparison with the usual str parse (e.g str(1)). But for my surprise, when I checked the velocity of both methods with the timeit function, I found out that >>> from timeit import timeit >>> timeit("f'{1}'") 0.1678762999999961 whereas >>> timeit("str(1)") 0.3216999999999999 or even the repr func, which in most of the cases is faster than str cast >>> timeit("repr(1)")

Can you overload the Python 3.6 f-string's “operator”?

戏子无情 提交于 2020-01-02 00:59:08
问题 In Python 3.6, you can use f-strings like: >>> date = datetime.date(1991, 10, 12) >>> f'{date} was on a {date:%A}' '1991-10-12 was on a Saturday' I want to overload the method receiving the '%A' above. Can it be done? For example, if I wanted to write a dumb wrapper around datetime , I might expect this overloading to look something like: class MyDatetime: def __init__(self, my_datetime, some_other_value): self.dt = my_datetime self.some_other_value = some_other_value def __fstr__(self,

Fixed digits after decimal with f-strings

百般思念 提交于 2019-12-29 02:22:14
问题 Is there an easy way with Python f-strings (PEP 498) to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %) For example, let's say I want to display 2 digits after the decimal place. How do I do that? a = 10.1234 f'{a:.2}' Out[2]: '1e+01' f'{a:.4}' Out[3]: '10.12' a = 100.1234 f'{a:.4}' Out[5]: '100.1' As you can see "precision" has changed meaning from "number of places after the decimal point" as is the case when

Why isn't it possible to use backslashes in f-strings?

蹲街弑〆低调 提交于 2019-12-23 22:42:48
问题 In Python >=3.6, f-strings can be used as a replacement for the str.format method. As a simple example, these are equivalent: '{} {}'.format(2+2, "hey") f'{2+2} {"hey"}' Disregarding format specifiers, I can basically move the positional arguments of str.format inside braces in an f-string. Note specifically that I am allowed to just put str literals in here, although it may seem a bit unwieldy. There are however some limitations. Specifically, backslashes in any shape or form are disallowed

How can i use f-string with a variable, not with a string literal?

北城以北 提交于 2019-12-17 20:58:25
问题 I want to use f-string with my string variable, not with string defined with a string literal, "..." . here is my code name=["deep","mahesh","nirbhay"] user_input = r"certi_{element}" # this string i ask from user for element in name: print(f"{user_input}") This code gives output: certi_{element} certi_{element} certi_{element} But I want: certi_{deep} certi_{mahesh} certi_{nirbhay} how can I do this? 回答1: f"..." strings are great when interpolating expression results into a literal , but you

f-strings giving SyntaxError?

被刻印的时光 ゝ 提交于 2019-12-17 06:51:50
问题 I am getting an error message with my Atom reader here, where it is suggesting the first print.(f"message") is delivering an error: File "/Users/permanentmajority/Desktop/Coding/learnpythonbook.py", line 75 print(f"Let's talk about {my_name}.") ^ SyntaxError: invalid syntax [Finished in 0.077s] Code: my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 #lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print(f"Let's talk about {my_name}.") print(f"He

f-strings giving SyntaxError?

我的梦境 提交于 2019-12-17 06:51:07
问题 I am getting an error message with my Atom reader here, where it is suggesting the first print.(f"message") is delivering an error: File "/Users/permanentmajority/Desktop/Coding/learnpythonbook.py", line 75 print(f"Let's talk about {my_name}.") ^ SyntaxError: invalid syntax [Finished in 0.077s] Code: my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 #lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print(f"Let's talk about {my_name}.") print(f"He

How to postpone/defer the evaluation of f-strings?

时间秒杀一切 提交于 2019-12-12 13:21:14
问题 I am using template strings to generate some files and I love the conciseness of the new f-strings for this purpose, for reducing my previous template code from something like this: template_a = "The current name is {name}" names = ["foo", "bar"] for name in names: print (template_a.format(**locals())) Now I can do this, directly replacing variables: names = ["foo", "bar"] for name in names: print (f"The current name is {name}") However, sometimes it makes sense to have the template defined

Number to string conversion with f-string without leading or trailing zeros?

允我心安 提交于 2019-12-11 16:02:17
问题 Update: as up to now (2019-09), masking leading or trailing zeros in decimal numbers formatted to string seems to be unsupported in Python. You will need to use a workaround to get something like '.01' from the number 0.0101 (assuming 3 decimal places desired). I would even argue that it's a good thing not to support such a format since I'd consider '0.01' be better in terms of readability than '.01' '0.010' carries information (3 digits of precision...) that is lost in '0.01' If desired

Display different numbers of decimals in an f-string depending on number's magnitude?

风格不统一 提交于 2019-12-11 14:48:45
问题 The goal is to use an f-string to round a float to a different number of decimal places based on the size of the number. Is there in-line f-string formatting that works like the following function? def number_format(x: float): if abs(x) < 10: return f"{x:,.2f}" # thousands seperator for consistency if abs(x) < 100: return f"{x:,.1f}" return f"{x:,.0f}" # this is the only one that actually needs the thousands seperator 回答1: Although it is not something that can go in-line in an f-string, the