标签: f-string

f字符串是否适用于Python 3.4?

这应该适用于Python 3.4:

>>> a='tttt'

>>> print(f'The value of a is {a}')

python string python-3.x f-string

3
推荐指数
3
解决办法
3676
查看次数

有没有办法在大括号内分解 f 字符串?

例如,如果我有

>>> name = f"{os.path.splitext(os.path.basename('/some/long/path/I/donot/need/to/some/config.bs'))[0]}.yaml"
'config.yaml'
Run Code Online (Sandbox Code Playgroud)

因为实际文本很少,所以在 79 个字符之前没有好地方可以换行。看来你不能这样做:

name = f"{os.path.splitext(os.path.basename(
    '/some/long/path/I/donot/need/to/some/config.bs'))[0]}.yaml"

>>> f"{os.path.splitext(os.path.basename(
  File "<stdin>", line 1
    f"{os.path.splitext(os.path.basename(
                                        ^
SyntaxError: EOL while scanning string literal
Run Code Online (Sandbox Code Playgroud)

我唯一能做的就是拆分命令,例如:

>>> fname = '/some/long/path/I/donot/need/to/some/config.bs'
>>> tempname = os.path.splitext(os.path.basename(
...     fname))[0]
>>> name = f'{tempname}.yaml'
>>> name
'config.yaml'
Run Code Online (Sandbox Code Playgroud)

还有其他选项可以拆分 f 字符串吗?

python python-3.x python-3.6 f-string

3
推荐指数
1
解决办法
1733
查看次数

使用 f 字符串舍入浮点数

使用 % 格式,我可以四舍五入字符串中的小数位数:

pi = 3.14159265
print('pi = %0.2f' %pi)
Run Code Online (Sandbox Code Playgroud)

在输出中(在终端中)这会给我:

pi = 3.14
Run Code Online (Sandbox Code Playgroud)

我可以使用 f-strings 来完成这个任务吗?此功能已在 Python 3.6 中添加

python string multiline f-string

3
推荐指数
2
解决办法
2386
查看次数

f 字符串中的转义单括号

我正在尝试按以下格式打印字符串:

"rob: {color: red  , number: 4}"
Run Code Online (Sandbox Code Playgroud)

使用 f 字符串填充三个值:

f"{name}: color: {color}  , number: {number}" #missing brackets
Run Code Online (Sandbox Code Playgroud)

这将打印:

"rob: color: red  , number: 4" #missing brackets
Run Code Online (Sandbox Code Playgroud)

但我不知道如何以我需要的方式转义单个括号。我知道{{}}可以让您转义括号,但这会将两者打印在字符串中的同一位置。我尝试了{ { }{ } }在各自的位置,但这只是引发了一个错误。

python f-string

3
推荐指数
1
解决办法
4178
查看次数

有没有办法在 f 字符串中包含注释?

mo 在 f 字符串中包含注释会很有用。例如,拿这个代码:

f"""
<a
   href="{ escape(url) }"
   target="_blank" { # users expect link to open in new tab }
>bla</a>
"""
Run Code Online (Sandbox Code Playgroud)

如果此代码等效于:

f"""
<a
   href="{ escape(url) }"
   target="_blank" 
>bla</a>
"""
Run Code Online (Sandbox Code Playgroud)

您可以在大括号之间包含完整的 Python 表达式,但似乎不能包含注释。我对么?有没有办法做到这一点?

python f-string

3
推荐指数
1
解决办法
317
查看次数

SyntaxError: f-string: 期待 '}'

我这里有问题。

我不知道为什么这段代码不起作用。

newline = '\n'
tasks_choosen = ['markup', 'media', 'python_api', 'script', 'style', 'vue']
print(f'{ newline }### Initializing project with the following tasks: { ' '.join(tasks_choosen) }.{ newline }')
Run Code Online (Sandbox Code Playgroud)

错误:

文件“new-gulp-project.py”,第 85 行

print(f'{ newline }### 使用以下任务初始化项目:{ ' '.join(tasks_choosen) }.{ newline }')

SyntaxError: f-string: 期待 '}'

谁能帮我?

谢谢

python syntax-error f-string

3
推荐指数
1
解决办法
4247
查看次数

我可以在解释器解析代码之前断言 python 版本吗?

我想通知用户他们应该使用哪个 python 版本:

import sys
assert sys.version_info >= (3, 6), "Use Python 3.6 or newer"
print(f"a format string")
Run Code Online (Sandbox Code Playgroud)

但是相反,运行上述文件会导致语法错误:

$ python fstring.py. # default python is 2.7
  File "fstring.py", line 3
    print(f"a format string")
                           ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

是否可以按文件执行此操作,而无需将所有 f 字符串包装在 try 块内?

python version-detection f-string

3
推荐指数
1
解决办法
319
查看次数

运行时错误:操作在 f 字符串语句中没有标识

我正在评估 pytorch 模型。它以以下方式给出结果

results = model(batch)
# results is a list of dictionaries with 'boxes', 'labels' and 'scores' keys and torch tensor values
Run Code Online (Sandbox Code Playgroud)

然后我尝试打印一些值来检查发生了什么

print(
    (
        f"{results[0]['boxes'].shape[0]}\n" # Returns how many boxes there is
        f"{results[0]['scores'].mean()}" # Mean credibility score of the boxes
    )
)
Run Code Online (Sandbox Code Playgroud)

这会导致错误

Exception has occurred: RuntimeError: operation does not have identity

让事情变得更加混乱的是,print有时只会失败。为什么会失败?

python torch f-string torchvision

3
推荐指数
1
解决办法
4055
查看次数

如何在 f 字符串中使用 lambda 函数并有条件返回值?

我已经用谷歌搜索了很多,但似乎找不到有关这个问题的任何信息,或者也许因为我是菜鸟,所以我没有搜索正确的关键字。我确实发现了一个问题,但它在 lambda 函数中使用了 f 字符串,这与我需要的完全相反。

所以我有一个名为的计数器标志tc,它检查两个数字的总和是否超过某个预定义的常数。计数器标志工作正常并且获取10正确。我不能做的是程序的下一部分。
我想直接检查条件并以 f 字符串返回它。
到目前为止我已经能够做到这一点。

timE = f"({(lambda x: x = 'next' if tc==1 else x = 'same')} day)"
print(timE)
Run Code Online (Sandbox Code Playgroud)

我得到的是

File "<fstring>", line 1
    ((lambda x: x = 'next' if tc==1 else x = 'same'))
                  ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我需要的是 if tcis 1 那么 lambda 函数应该返回nextelse same。然后我需要的最终结果是(next day)or (same day)

我确实尝试了其他一些事情,它不会给我错误,但会给我其他东西。

timE = f"({(lambda : 'next' if tc==1 else 'same')} day)" …
Run Code Online (Sandbox Code Playgroud)

lambda string-formatting python-3.x f-string

3
推荐指数
1
解决办法
4510
查看次数

存储格式化字符串,稍后传入值?

我有一本有很多字符串的字典。

是否可以存储带有占位符的格式化字符串并稍后传入实际值?

我在想这样的事情:

d = {
  "message": f"Hi There, {0}"
}

print(d["message"].format("Dave"))
Run Code Online (Sandbox Code Playgroud)

上面的代码显然不起作用,但我正在寻找类似的东西。

python templates string-formatting python-3.x f-string

3
推荐指数
1
解决办法
3700
查看次数