考虑以下代码片段:
name1 = "Nadya"
name2 = "Jim"
def print_string():
string = f"{name1}\n\
{name2}"
print(string)
print_string()
Run Code Online (Sandbox Code Playgroud)
产生
Nadya
Jim
Run Code Online (Sandbox Code Playgroud)
这有效,但string定义第二行缩进中的“中断”看起来很难看。我发现如果我缩进{name2}一行,这个缩进会出现在最后的字符串中。
我正在尝试找到一种方法来在新行上继续 f 字符串并缩进它,而不会在最终字符串中显示缩进。遵循我在普通字符串中看到的类似内容,我尝试过
name1 = "Nadya"
name2 = "Jim"
def print_string():
string = f"{name1}\n"
f"{name2}"
print(string)
print_string()
Run Code Online (Sandbox Code Playgroud)
但这会导致IndentationError: unexpected indent. 我正在尝试以另一种方式可能吗?
我有我自己的个人数据库,我为了好玩(所以不关心 sql 注入,因为它是我自己创建的私有数据库),并且正在尝试更改我创建的使用字符串格式 (.format()) 和占位符 (? 、%s 等)并使用 f 字符串代替。我遇到了一个问题,现在我将 sqlite3 查询更改为 f 字符串后,我的一个将指定列更新为指定行的函数将无法运行。
这是我当前使用 f 字符串的函数:
import sqlite3
from tabulate import tabulate
conn = sqlite3.connect("Table.db")
c = conn.cursor()
def updatedb(Column, Info, IdNum):
with conn:
data = c.execute(f"UPDATE Table_name SET {Column} = {Info} WHERE IdNum={IdNum}")
c.execute(f"SELECT * FROM Table_name WHERE IdNum = {IdNum}")
print(tabulate(data, headers="keys", tablefmt="grid", stralign='center', numalign='center'))
Run Code Online (Sandbox Code Playgroud)
该函数通过使用您想要的列中的新信息更新指定行的指定列来更新表。例如,在 3 x 3 表中,如果该列是年龄或其他内容,我可以使用该函数将第 1 行第 2 列更新为第 18 行,而不是第 1 行第 2 列。之后的选择查询只是选择更新的特定行,之后的打印语句使用 tabulate 包打印出一个整洁有序的表格。
每当我尝试使用此功能时出现的错误是:
sqlite3.OperationalError: no such column: …Run Code Online (Sandbox Code Playgroud) 在大部分时间使用 VSCode 之后,我将切换回使用 VS2017 进行大部分 Python 开发。在 VSCode 中,我能够很好地使用带有语法高亮和智能感知的 f 字符串。
在 VS2017 中,当我使用 f 字符串时,它只会显示为原始字符串而不突出显示。这在程序运行时有效,但对于调试和编写,它使事情变得更加痛苦。
有谁知道这是否可以添加到VS2017?两者都在运行 python 3.6,所以我认为不应该有问题。
为了澄清,我指的是这些:
f'Hello My Name Is { user.Name }'
Run Code Online (Sandbox Code Playgroud) 如果我有一个 yaml 文件,其中包含一个带有括号符号 {} 的字符串,与 python f 字符串配合使用,那么如何在此处利用 f 字符串插值?以这个简单的 yaml 文件为例:
# tmp.yaml
k1: val1
k2: val2 as well as {x}
Run Code Online (Sandbox Code Playgroud)
如果x = 'val3',我希望 k2 的值能够反映val2 as well as val3
# app.py
x = 'val3'
with open('tmp.yaml', 'rt') as f:
conf = yaml.safe_load(f)
print(conf)
{'k1': 'val1', 'k2': 'val2 as well as {x}'}
Run Code Online (Sandbox Code Playgroud)
这可以通过格式字符串很容易地完成......
print(conf['k2'].format(x=x))
val2 as well as val3
Run Code Online (Sandbox Code Playgroud)
但如何对 f 字符串执行同样的操作呢?
我是 PHP 新手,所以请原谅这个问题。
我想知道 PHP 是否有字符串格式函数,例如 Python 的 f-strings 函数,而不是 str.format()。我看过一些关于这个主题的帖子,但大多数被接受为答案的例子是指 Python 处理格式化字符串的旧方式str.format()。在我的情况下,我想使用格式化的字符串构建一个变量,例如(Python):
f_name = "John"
l_name = "Smith"
sample = f`{f_name}'s last name is {l_name}.`
print(sample)
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用(PHP):
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
Run Code Online (Sandbox Code Playgroud)
但是如果我想$format用作变量呢?主要思想是基于其他变量创建一个动态变量,例如:
$db_type = $settings['db_type']; # mysql
$db_host = $settings['db_host']; # localhost
$db_name = $settings['db_name']; # sample
var $format = "%s:host=%s; dbname=%s";
# Not sure what to do after that, …Run Code Online (Sandbox Code Playgroud) Python 3.8 允许使用自记录表达式和调试=,例如:
print(f'{myvar=}')
Run Code Online (Sandbox Code Playgroud)
是否可以在新行上打印输出?这对于具有多行输出的变量(例如数据框)非常有用,例如
import pandas as pd
df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion', 'monkey']})
print(f'{df=}')
Run Code Online (Sandbox Code Playgroud)
df =
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
Run Code Online (Sandbox Code Playgroud) 当我以类似的方式使用带有格式说明符的 f 字符串时
>>> x = 1
>>> f'{ x:02 }'
Run Code Online (Sandbox Code Playgroud)
它给了我ValueError: Unknown format code '\x20' for object of type 'int'。为了解决这个问题,我必须从 f 字符串表达式中删除周围的空格,例如f'{x:02}'.
为什么会这样呢?
这两个print语句产生相同的结果,至少对我来说,第一个版本看起来更具可读性。
我是否应该坚持使用该f'版本,因为它会在以后给我带来问题,或者导致性能更差,或者不遵循当前的 Python 标准?或者这只是这些版本之一的一致使用问题?
print('My first bicycle was a ' + bicycles[1])
print(f'My first bicycle was a {bicycles[1]})')
Run Code Online (Sandbox Code Playgroud) 在 python3.8 中,一个新功能是自记录格式字符串。人们通常会这样做:
>>> x = 10.583005244
>>> print(f"x={x}")
x=10.583005244
Run Code Online (Sandbox Code Playgroud)
现在可以减少重复次数来做到这一点:
>>> x = 10.583005244
>>> print(f"{x=}")
x=10.583005244
Run Code Online (Sandbox Code Playgroud)
这对于单行字符串表示非常有效。但请考虑以下场景:
>>> import numpy as np
>>> some_fairly_long_named_arr = np.random.rand(4,2)
>>> print(f"{some_fairly_long_named_arr=}")
some_fairly_long_named_arr=array([[0.05281443, 0.06559171],
[0.13017109, 0.69505908],
[0.60807431, 0.58159127],
[0.92113252, 0.4950851 ]])
Run Code Online (Sandbox Code Playgroud)
在这里,第一行没有对齐,这(可以说)是不可取的。我更喜欢以下输出:
>>> print(f"some_fairly_long_named_arr=\n{some_fairly_long_named_arr!r}")
some_fairly_long_named_arr=
array([[0.05281443, 0.06559171],
[0.13017109, 0.69505908],
[0.60807431, 0.58159127],
[0.92113252, 0.4950851 ]])
Run Code Online (Sandbox Code Playgroud)
在这里,输出的第一行也对齐了,但是它违背了在 print 语句中不重复变量名称两次的目的。
该示例是一个 numpy 数组,但它也可能是一个 pandas 数据框等。
=因此,我的问题是:可以在自记录字符串的符号后面插入换行符吗?
我尝试像这样添加它,但它不起作用:
>>> print(f"{some_fairly_long_named_arr=\n}")
SyntaxError: f-string expression part cannot include a backslash
Run Code Online (Sandbox Code Playgroud)
我阅读了format-specation-mini-language 上的文档,但其中的大多数格式仅适用于整数等简单数据类型,并且我无法使用那些有效的数据类型来实现我想要的效果。
我正在尝试在 f 字符串中使用命名表达式:
print(f"{(a:=5 + 6) = }")
Run Code Online (Sandbox Code Playgroud)
返回:
(a:=5 + 6) = 11
Run Code Online (Sandbox Code Playgroud)
但我希望有这样的事情:
a = 11
Run Code Online (Sandbox Code Playgroud)
通过组合海象运算符和 f 字符串是否可能(这样我就不必a在单独的步骤中首先声明变量)?
python string-interpolation python-3.x f-string walrus-operator