在没有输出缩进的函数内定义一个包含换行符的三引号 f 字符串
Define a triple-quoted f-string with newline-containing substrings inside a function without outputted indents
我正在尝试漂亮地打印一个 HTTP 请求(我在这里嘲笑过)。
from typing import NamedTuple
class RequestMock(NamedTuple):
method = 'POST'
url = 'https://bob.com'
body = 'body1\nbody2'
headers = {'a': '1', 'b': '2'}
我有一个函数可以做到这一点:
req = RequestMock()
def print1(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = '\n'.join([
f'{req.method} {req.url}',
headers,
req.body
])
print(s)
print1(req)
# POST https://bob.com
# a: 1
# b: 2
# body1
# body2
但是当我试图用 f-strings
重写它时为了清晰和易于修改,我得到了一些错误的缩进:
# what I want the code to look like
def print2(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = f"""
{req.method} {req.url}
{headers}
{req.body}
"""
print(s)
print2(req)
# POST https://bob.com
# a: 1
# b: 2
# body1
# body2
我知道这是因为我用换行符定义字符串并将它们放在三引号字符串中。有没有一种简单的方法可以使用函数中定义的三引号 f-string
来获取我正在查看的输出,而不必知道其定义的缩进级别?我玩过 textwrap.indent
、textwrap.dedent
、str.lstrip
、re
等,但代码不再简单和 pythonic 快速。我想到的最接近的是下面的,但是长度很尴尬,我觉得我在重复自己。
def print3(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = textwrap.dedent("""
{method} {url}
{headers}
{body}
""").strip()
s = s.format(
method=req.method,
url=req.url,
headers=headers,
body=req.body,
)
print(s)
print3(req)
# POST https://bob.com
# a: 1
# b: 2
# body1
# body2
我认为您可以尝试利用隐式字符串连接来获得半漂亮的解决方案:
def print4(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = (f'{req.method} {req.url}\n'
f'{headers}\n'
f'{req.body}')
print(s)
print4(req)
输出:
POST https://bob.com
a: 1
b: 2
body1
body2
请注意,如果需要,可以去掉括号并使用反斜杠:
s = f'{req.method} {req.url}\n' \
f'{headers}\n' \
f'{req.body}'
但是,样式指南更喜欢使用圆括号而不是反斜杠。
另一个选项:
def print5(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = f"""
{req.method} {req.url}
{headers}
{req.body}
"""
s = '\n'.join(l.lstrip() for l in s.splitlines())
print(s)
您可以通过 2 个微小的更改来修复它:
def print6(req, **w):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
method, url, body = \
w['method'], w['url'], w['body']
# < note the changes belowwwwwwwwwwww >
s = '\n'.join(line.lstrip() for line in f"""
{method} {url}
{headers}
{body}
""".split('\n')) # and note this .split('\n') over here
print(s)
print6(req)
我正在尝试漂亮地打印一个 HTTP 请求(我在这里嘲笑过)。
from typing import NamedTuple
class RequestMock(NamedTuple):
method = 'POST'
url = 'https://bob.com'
body = 'body1\nbody2'
headers = {'a': '1', 'b': '2'}
我有一个函数可以做到这一点:
req = RequestMock()
def print1(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = '\n'.join([
f'{req.method} {req.url}',
headers,
req.body
])
print(s)
print1(req)
# POST https://bob.com
# a: 1
# b: 2
# body1
# body2
但是当我试图用 f-strings
重写它时为了清晰和易于修改,我得到了一些错误的缩进:
# what I want the code to look like
def print2(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = f"""
{req.method} {req.url}
{headers}
{req.body}
"""
print(s)
print2(req)
# POST https://bob.com
# a: 1
# b: 2
# body1
# body2
我知道这是因为我用换行符定义字符串并将它们放在三引号字符串中。有没有一种简单的方法可以使用函数中定义的三引号 f-string
来获取我正在查看的输出,而不必知道其定义的缩进级别?我玩过 textwrap.indent
、textwrap.dedent
、str.lstrip
、re
等,但代码不再简单和 pythonic 快速。我想到的最接近的是下面的,但是长度很尴尬,我觉得我在重复自己。
def print3(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = textwrap.dedent("""
{method} {url}
{headers}
{body}
""").strip()
s = s.format(
method=req.method,
url=req.url,
headers=headers,
body=req.body,
)
print(s)
print3(req)
# POST https://bob.com
# a: 1
# b: 2
# body1
# body2
我认为您可以尝试利用隐式字符串连接来获得半漂亮的解决方案:
def print4(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = (f'{req.method} {req.url}\n'
f'{headers}\n'
f'{req.body}')
print(s)
print4(req)
输出:
POST https://bob.com
a: 1
b: 2
body1
body2
请注意,如果需要,可以去掉括号并使用反斜杠:
s = f'{req.method} {req.url}\n' \
f'{headers}\n' \
f'{req.body}'
但是,样式指南更喜欢使用圆括号而不是反斜杠。
另一个选项:
def print5(req):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
s = f"""
{req.method} {req.url}
{headers}
{req.body}
"""
s = '\n'.join(l.lstrip() for l in s.splitlines())
print(s)
您可以通过 2 个微小的更改来修复它:
def print6(req, **w):
headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
method, url, body = \
w['method'], w['url'], w['body']
# < note the changes belowwwwwwwwwwww >
s = '\n'.join(line.lstrip() for line in f"""
{method} {url}
{headers}
{body}
""".split('\n')) # and note this .split('\n') over here
print(s)
print6(req)