我想使用传递给format方法的变量计算f-string中的数学运算.例如,我需要这样的东西:
print(f"{{a}} * 3".format(a=2))
Run Code Online (Sandbox Code Playgroud)
此代码打印:
2 * 3
Run Code Online (Sandbox Code Playgroud)
但我想要的结果是6.另外我不会使用python eval函数来评估这个字符串.
我正在尝试使用 python 3.6 的新 f-string 功能在墙上编写自己的 99 瓶啤酒实现,但我被卡住了:
def ninety_nine_bottles():
for i in range(10, 0, -1):
return (f'{i} bottles of beer on the wall, {i} of beer! You take one down, pass it around, {} bottles of beer on the wall')
Run Code Online (Sandbox Code Playgroud)
如何减少最后一对括号中的“i”?我试过 i-=1 无济于事(语法错误)...
由于缺乏更好的词汇,我选择了这个头衔.
我想要的是能够做这样的事情:
>>> from random import randint
>>> fruits = [
... "Orange",
... "Banana",
... f"{randint(2,5)} Cherries",
... ]
>>> fruits[2]
'3 Cherries'
>>> fruits[2]
'5 Cherries'
>>> fruits[2]
'2 Cherries'
Run Code Online (Sandbox Code Playgroud)
但相反,字符串中的文字表达式在创建列表时会被评估一次,并在每次访问时得到相同的结果.
我想知道除了编写一些复杂的边缘案例处理之外是否还有一种更容易/更聪明的方法来解决这个问题(毕竟我们是程序员;谁不喜欢编写漂亮的代码并且优雅和喜欢?).我说的是边缘案例处理,因为我的49个字符串中只有6个需要这种"特殊"行为.
到目前为止我所尝试的是从randint调用中创建一个lambda函数,但这并没有帮助; 同样的结果.也许这是懒惰评估的一个案例,但我需要一些指导如何(或是否?)将它与列表一起使用.
我可以这样创建b-sting:
name_binary = b'Adam'
但是,如果我有变量like,name='Adam'并且想立即使用f-string和b-string:
name_binary = fb'{name}'
我得到:
File "<input>", line 1
c = fb'{a}'
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
我知道我可以做到:
name_binary = name.encode('utf-8')
但是像我的例子一样,通过同时使用b和f可以实现技术性吗?
这个问题来自处理jupyter magics,但可以用更简单的方式表达。给定一个字符串s = "the key is {d['key']}"和一个字典d = {'key': 'val'},我们想解析这个字符串。
旧方法是.format(),这会引发错误 - 它不处理字典键。
"the key is {d['key']}".format(d=d) # ERROR
Run Code Online (Sandbox Code Playgroud)
我认为唯一的方法是将字典转换为对象(在此处或此处解释)。
"the key is {d.key}".format(obj(d))
Run Code Online (Sandbox Code Playgroud)
但是Martijn很好地解释了,您可以简单地省略引号以使其正常工作:
"the key is {d[key]}".format(d=d)
Run Code Online (Sandbox Code Playgroud)
新方法仍然f'string'以直观的 Python 方式处理字典键:
f"the key is {d['key']}"
Run Code Online (Sandbox Code Playgroud)
它还处理功能——某些东西.format也无法处理。
f"this means {d['key'].lower()}"
Run Code Online (Sandbox Code Playgroud)
虽然我们现在知道你可以用来做.format,但我仍然想知道最初的问题:给定s和d,你如何强制f'string'解析s?我在大括号内添加了另一个带有函数的示例,该示例.format也无法处理并且f'string'能够解决。
是否有一些功能.fstring()或方法可用?Python 内部使用什么?
大多数情况下,我使用Python3。我可以写这个吗
print(f"the answer is {21 + 21} !")
Run Code Online (Sandbox Code Playgroud)
输出:答案是42!但是在Python 2中f字符串不存在。那么这是最好的方法吗?
print("the answer is " + str(21 + 21) + "!")
Run Code Online (Sandbox Code Playgroud) 我们如何在 python 中显示人类可读的字节大小?
我们需要转换大量不可读的int结果,例如os.stat(r'C:\1.pdf').st_size
(下面用 3.6 以上的 python 版本的 f-strings 回答我自己的问题,如果它们适用于其他 python 版本或其他格式化方式,请添加您自己的答案)
我正在尝试处理 f 字符串中的错误,但我的尝试似乎不起作用。有没有办法做到这一点?
string = f"For example I thought this syntax would work but it doesn't {try: 5/0 except Exception: str(infinity)}"
Run Code Online (Sandbox Code Playgroud) 我想在 python3 的 f 字符串中打印一条消息,其中包含一个由 \n 分隔的列表。
my_list = ["Item1", "Item2", "Item3"]
print(f"Your list contains the following items:\n\n{my_list}")
Run Code Online (Sandbox Code Playgroud)
期望的输出:
# Your list contains the following items:
# Item1
# Item2
# Item3
Run Code Online (Sandbox Code Playgroud) 说我有一个字符串 -
my_str = "From {country} with Love"
变量country目前不可用,稍后将设置为
country = "Russia".
现在我可以用动态解析的内联变量值打印字符串吗?就像是 -
print(f"{my_str}")
这将输出
From Russia with Love
我尝试使用 eval() 但没有帮助。