动态更改其中一个 f 字符串变量
Dynamically change one of f-string variables
有没有办法动态 change/substitute 一个 f 字符串变量?
假设我的格式如下:
expected = f'{var} {self.some_evaluation_1(var)} {self.some_evaluation_2(var)}'
然后我有多个断言的测试用例:
var1='some value 1'
var2='some value 2'
var3='some value 3'
var=var1
self.assertEqual('some great value1', expected)
var=var2
self.assertEqual('some great value2', expected)
var=var3
self.assertEqual('some great value3', expected)
有没有办法让 f 字符串使用我的变量而不是在初始格式中定义?
# Let's say something like this? It's just a concept I know it doesn't work.
self.assertEqual('some great value1', expected % var1)
不,f 字符串表达式的结果是 不可变 字符串。类似于:
y = 'abc'
x = y + 'def' # result of expression is immutable string.
y = 'ghi'
print(x) # would you expect 'ghidef'? No...
如果你想改变它,使用 format
而不是 f-strings 来重新计算 expected
:
expected = 'test{}' # NOT an f-string
var = 1
assert expected.format(var) == 'test1'
var = 2
assert expected.format(var) == 'test2'
如果您在示例中命名了变量,则可以使用:
expected = 'test{var}'
assert expected.format(var=1) == 'test1'
或使用关键字扩展 (**) 将 locals()
作为参数字典传递:
expected = 'test{a}{b}'
a = 1
b = 2
assert expected.format(**locals()) == 'test12'
有没有办法动态 change/substitute 一个 f 字符串变量? 假设我的格式如下:
expected = f'{var} {self.some_evaluation_1(var)} {self.some_evaluation_2(var)}'
然后我有多个断言的测试用例:
var1='some value 1'
var2='some value 2'
var3='some value 3'
var=var1
self.assertEqual('some great value1', expected)
var=var2
self.assertEqual('some great value2', expected)
var=var3
self.assertEqual('some great value3', expected)
有没有办法让 f 字符串使用我的变量而不是在初始格式中定义?
# Let's say something like this? It's just a concept I know it doesn't work.
self.assertEqual('some great value1', expected % var1)
不,f 字符串表达式的结果是 不可变 字符串。类似于:
y = 'abc'
x = y + 'def' # result of expression is immutable string.
y = 'ghi'
print(x) # would you expect 'ghidef'? No...
如果你想改变它,使用 format
而不是 f-strings 来重新计算 expected
:
expected = 'test{}' # NOT an f-string
var = 1
assert expected.format(var) == 'test1'
var = 2
assert expected.format(var) == 'test2'
如果您在示例中命名了变量,则可以使用:
expected = 'test{var}'
assert expected.format(var=1) == 'test1'
或使用关键字扩展 (**) 将 locals()
作为参数字典传递:
expected = 'test{a}{b}'
a = 1
b = 2
assert expected.format(**locals()) == 'test12'