我喜欢保留一个文件,其中仅包含代表 SQL 查询的 f 字符串,并且每个查询都需要一个数据库名称。在我的 python 程序中,我将在读取数据库名称时填充 db 变量。
例如queries.py,我有
query_1 = f"select * from {db} limit 10;"
Run Code Online (Sandbox Code Playgroud)
在main.py,我用
from quries import quries
# read out db information into dbs
for db in dbs:
# execute the query_1 for each db
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现循环中的逻辑?
我想构建一个工具,将 fstring 格式存储在配置文件中。
config = load_config()
def build_fstring(str):
return ... # <-- issue is there
chosen_format = config.get("chosen_format") # returns '{k},{v}'
fstring = build_fstring(chosen_format) # may return something like 'f"{k},{v}"'
for (k,v) in d.items():
print(fstring) # fstring is evaluated here
Run Code Online (Sandbox Code Playgroud)
我的问题是 fstring 是在变量已知之前编译的。
有办法做到吗?
我知道我可以做到以下几点。但是是否有可能将它们结合起来给我一个带有固定小数的百分比?
>>> print(f'{0.123:%}')
12.300000%
>>> print(f'{0.123:.2f}')
0.12
Run Code Online (Sandbox Code Playgroud)
但我想要的是这个输出:
12.30%
Run Code Online (Sandbox Code Playgroud) 我试图将“$”和totalTransactionCost 移至该字段的右侧。
我当前的代码是:print(f"Total Cost Of All Transactions: ${totalTransactionCost:>63,.2f}")
该代码能够将totalTransactionCost 移至字段的右侧,但如何也包含“$”?
我在使用Python 3.7.
我在第3行的代码工作正常,但是当我将基础公式插入第4行时,我的代码返回错误:
SyntaxError:f-string:mismatched'(','{'或'[' (错误指向第一个'('第4行'.
我的代码是:
cheapest_plan_point = 3122.54
phrase = format(round(cheapest_plan_point), ",")
print(f"1: {phrase}")
print(f"2: {format(round(cheapest_plan_point), ",")}")
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚第4行有什么问题.
要将某些数字打印为二进制格式,我们只需使用.format()方法,如下所示:
# Binary
for i in range(5+1):
print("{0:>2} in binary is {0:>08b}".format(i))
0 in binary is 00000000
1 in binary is 00000001
2 in binary is 00000010
3 in binary is 00000011
4 in binary is 00000100
5 in binary is 00000101
Run Code Online (Sandbox Code Playgroud)
对于其他格式(十六进制和八进制)的打印也是如此,只需要将后者的花括号替换为我们要打印的数字即可。但是,有没有办法使用新f""字符串替换.format()命令?我知道这看似微不足道,但我在试用新功能时不胜其烦,此外还f""使代码更短,更易读。
for i in range(5+1):
print(f'{0:>2} in binary is {0:>08b}')
# This prints out just 0s
Run Code Online (Sandbox Code Playgroud) 我喜欢 python 3.6 中的新 f-Strings,但是在尝试在表达式中返回 String 时我看到了一些问题。下面的代码不起作用并告诉我我使用了无效的语法,即使表达式本身是正确的。
print(f'{v1} is {'greater' if v1 > v2 else 'less'} than {v2}') # Boo error
Run Code Online (Sandbox Code Playgroud)
它告诉我,'greater'并且'less'是意料之外的标记。如果我用两个包含字符串的变量甚至两个整数替换它们,错误就会消失。
print(f'{v1} is {10 if v1 > v2 else 5} than {v2}') # Yay no error
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么?
如何在f-string 中插入for循环或if表达式?
我最初想为if表达式做这样的事情:
f'{a:{"s" if CONDITION else "??"}}'
Run Code Online (Sandbox Code Playgroud)
我想做的是:
示例 1
f'{key: value\n for key, value in dict.items()}'
Run Code Online (Sandbox Code Playgroud)
结果:
如果 dict = {'a': 1, 'b': 2}
a: 1
b: 2
Run Code Online (Sandbox Code Playgroud)
或示例 2
c = 'hello'
f'{c} {name if name else "unknown"}'
Run Code Online (Sandbox Code Playgroud)
结果:
如果名称存在,例如 name = 'Mike'
hello Mike
Run Code Online (Sandbox Code Playgroud)
除此以外
hello unknown
Run Code Online (Sandbox Code Playgroud)
这可以做到吗?如果是,怎么做?
我一直在搞文本对齐,包括字符串方法和 f 字符串。我目前的目标是创建一个目录样式的输出,看起来像这样:
Introduction....................1
Python Basics...................5
Creating Your First Program....12
Operators and Variables........29
Run Code Online (Sandbox Code Playgroud)
很容易,我已经能够将其格式化为:
Introduction 1
Python Basics 5
Creating Your First Program 12
Operators and Variables 29
Run Code Online (Sandbox Code Playgroud)
代码是:
Introduction....................1
Python Basics...................5
Creating Your First Program....12
Operators and Variables........29
Run Code Online (Sandbox Code Playgroud)
我在网上找不到任何描述如何将填充字符和 f 字符串添加在一起的资源。使用.center, .ljust,.rjust字符串方法,我已经能够做到这一点,因为它们采用宽度参数,然后是一个可选的填充字符。在这篇文章中,我以为我找到了解决方案。
该
x<y部分表示将文本左对齐,宽度为 y 个空格。对于任何未使用的空间,用字符 x 填充它。
我尝试了这种方法,将我的打印语句从 编辑print(f"{chapt:<30}{page:>5}")为print(f"{chapt:'.'<30}{page:'.'>5}")。然而这会返回一个错误:
Traceback (most recent call last):
File "main.py", line 40, in <module>
print(f"{chapt:'.'<30}{page:'.'>5}")
ValueError: Invalid format specifier
Run Code Online (Sandbox Code Playgroud)
(第 …
有什么办法可以将 {} 显示为 f 字符串的一部分,因为它在 f 字符串中具有特殊含义。换句话说:
如果运行print(f"hello world {}"),我想要这样的结果hello world {}
我尝试的解决方案是:print(f"hello world \{\}"). 但它没有用。
非常感谢您的帮助