[英]String formatting with f-string
I just want to do something for transformation my string into view like: (2 ** 5)(5)(7 ** 2)(11), but my code works wrong.我只想做一些事情来将我的字符串转换为视图,例如:(2 ** 5)(5)(7 ** 2)(11),但我的代码工作错误。 tell me please, where are my mistakes?!请告诉我,我的错误在哪里?!
values = [(2, 5), (5, 1), (7, 2), (11, 1)]
result = str(f'({i[0]}**{i[1]})' for i in values if i[1] != 1 else f'({i[0]})')
print(result) # (2 ** 5)(5)(7 ** 2)(11)
this is a variant:这是一个变体:
values = [(2, 5), (5, 1), (7, 2), (11, 1)]
result = ''.join(f'({base} ** {exp})' if exp != 1 else f'({base})'
for base, exp in values)
print(result) # (2 ** 5)(5)(7 ** 2)(11)
where i use tuple unpacking to assign base
and exp
to the items of your list and then str.join (in the form ''.join(...)
) to join the individual terms.我使用元组解包将base
和exp
分配给列表中的项目,然后str.join (以''.join(...)
形式)加入各个条款。
so in the first iteration you get base=2, exp=5
which will be converted to the string '(2 ** 5)'
;所以在第一次迭代中你得到base=2, exp=5
这将被转换为字符串'(2 ** 5)'
; on the second iteration you get base=5, exp=1
which will be converted to the string '(5)'
(and so on);在第二次迭代中,您得到base=5, exp=1
,它将被转换为字符串'(5)'
(依此类推); then these strings will be joined with ''
(ie an empty string) in between.然后这些字符串将在它们之间用''
(即空字符串)连接。
Place your ternary operator before the list comprehension part:将三元运算符放在列表理解部分之前:
result = "".join([
f'({i[0]} ** {i[1]})' if i[1] != 1 else f'({i[0]})'
for i in values
])
print(result) # (2 ** 5)(5)(7 ** 2)(11)```
that is my decision.这是我的决定。 thank to all!谢谢大家!
result = ''.join('({} ** {})'.format(i[0], i[1]) if i[1] != 1 else '({})'.format(i[0]) for i in values)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.