关于 python f 字符串的基本问题,但找不到答案:如何强制浮点数或整数的符号显示?即什么 f 字符串使3显示为+3?
说我有一个功能
def foo(): return [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我想将函数的结果插入到字符串中以获取"001 002 003".我试过这个:
f"{*foo():03d 03d 03d}"
Run Code Online (Sandbox Code Playgroud)
但它产生了SyntaxError: can't use starred expression here.我可以用f-string做这个吗?
如果我只使用原始字符串但是只要将f添加到r,此代码就可以工作.它停止工作.有没有办法让f字符串与原始字符串一起工作?
import re
lines = '''
04/20/2009; 04/20/09; 4/20/09; 4/3/09
Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009;
20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009
Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009
Feb 2009; Sep 2009; Oct 2010
6/2008; 12/2009
2009; 2010
'''
rmonth = 'a'
regex = fr'(\d{1,2})/(\d{1,2})/(\d{4}|\d{2})'
date_found = re.findall(regex, lines)
date_found
Run Code Online (Sandbox Code Playgroud) 我在一个项目中找到了以下代码。
什么是!r部分是什么意思?
def __repr__(self):
return f"user={self.user!r}, variant={self.variant!r}"
Run Code Online (Sandbox Code Playgroud) 我在这里收到了我的Atom阅读器的错误消息,其中建议第一个print.(f"message")是发送错误:
File "/Users/permanentmajority/Desktop/Coding/learnpythonbook.py", line 75
print(f"Let's talk about {my_name}.")
^
SyntaxError: invalid syntax
[Finished in 0.077s]
Run Code Online (Sandbox Code Playgroud)
码:
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 #lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {my_eyes} eyes and {my_hair} hair.")
print(f"His teeth are usually {my_teeth} depending on …Run Code Online (Sandbox Code Playgroud) 我正在尝试漂亮地打印一个 HTTP 请求(我在这里嘲笑过)。
from typing import NamedTuple
class RequestMock(NamedTuple):
method = 'POST'
url = 'https://bob.com'
body = 'body1\nbody2'
headers = {'a': '1', 'b': '2'}
Run Code Online (Sandbox Code Playgroud)
我有一个函数可以执行此操作:
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
Run Code Online (Sandbox Code Playgroud)
f-strings但是,当我为了清晰和易于修改而尝试重写它时,我得到了一些不好的缩进:
# what I want the code to look like
def print2(req):
headers = '\n'.join(f'{k}: {v}' for …Run Code Online (Sandbox Code Playgroud) 在最近的Python 3.6版本中使用新的f字符串时,我注意到以下内容:
我们创建一个foo值为的变量bar:
>>> foo = 'bar'
Run Code Online (Sandbox Code Playgroud)然后,我们声明一个新变量,它是我们的f-string,它应该foo被格式化:
>>> baz = f'Hanging on in {foo}'
Run Code Online (Sandbox Code Playgroud)好的,一切正常,然后我们打电话baz来检查它的价值:
>>> baz
'Hanging on in bar'
Run Code Online (Sandbox Code Playgroud)让我们尝试更改值foo并baz再次调用:
>>> foo = 'spam'
>>> baz
'Hanging on in bar'
Run Code Online (Sandbox Code Playgroud)它不应该是动态的吗?为什么会这样?我认为如果foo改变了值,f-string会更新,但是这没有发生.我不明白这是如何工作的.
如何使用带有逻辑的f-string格式化int为float?我想ppl是True格式化num为2位小数,如果ppl是False格式化为它是什么.
有点像string = f'i am {num:.2f if ppl else num}'但这不起作用.下面的代码演示了如果可能的话我想用更简单的f字符串实现的行为:
ppl = True
num = 3
string = f'I am {num:.2f}' if ppl else f'I am {num}'
print(string)
#if ppl False
#=> i am 3
#if ppl True
#=> i am 3.00
Run Code Online (Sandbox Code Playgroud) 我有以下f-string我想在变量可用的条件下打印出来:
f"Percent growth: {self.percent_growth if True else 'No data yet'}"
Run Code Online (Sandbox Code Playgroud)
结果如下:
Percent growth : 0.19824077757643577
Run Code Online (Sandbox Code Playgroud)
所以我通常会使用类型说明符来表示float精度:
f'{self.percent_growth:.2f}'
Run Code Online (Sandbox Code Playgroud)
这将导致:
0.198
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,这与if语句混淆了.它失败的原因是:
f"Percent profit : {self.percent_profit:.2f if True else 'None yet'}"
Run Code Online (Sandbox Code Playgroud)
if语句变得无法访问.或者以第二种方式:
f"Percent profit : {self.percent_profit if True else 'None yet':.2f}"
Run Code Online (Sandbox Code Playgroud)
只要条件导致else子句,f-string就会失败.
所以我的问题是,当f-string可以产生两种类型时,如何在f-string中应用float精度?
在 Python 3.6 中,有一个新的 f-string 在字符串中包含变量,这很棒,但是如何正确应用这些字符串来为 matplotlib 打印上标或下标?
(要实际看到带有下标的结果,您需要foo在 matplotlib 图上绘制变量)
换句话说,我如何获得这种行为:
var = 123
foo = r'text$_{%s}$' % var
text<sub>123</sub>
Run Code Online (Sandbox Code Playgroud)
使用新的 f-string 语法?到目前为止,我已经尝试将原始字符串文字与 f 字符串结合使用,但这似乎只是将下标应用于变量的第一个字符:
var = 123
foo = fr'text$_{var}$'
text<sub>1</sub>23
Run Code Online (Sandbox Code Playgroud)
因为 the{有一个不明确的功能,作为分隔r应该考虑的下标和分隔f变量的地方。
f-string ×10
python ×9
python-3.x ×6
string ×3
python-3.6 ×2
formatting ×1
matplotlib ×1
python-2.x ×1
regex ×1
syntax-error ×1