自动将字符串转为格式化字符串? (Python)

问题描述 投票:0回答:1

我想编写一个备用 print() 函数,它自动将输入的字符串转换为格式化字符串,并具有正确的变量格式。

那么为什么这不起作用?

Test = 'Hello!'

def prints(druck):
    for el in druck.split():
        print(f'{el}')

prints('Hello? Test')

输出为:

Hello?
Test

我想要的输出是:

Hello?
Hello!

目前我只在 prints() 中放入了一个单词。最后,我希望能够在较长的字符串中打印变量,而不必使用 {} 它们。

我的梦想是有一个 print() 函数来检查一个单词是否是一个变量(类似于 if el == {el}?)并正确打印出来,无论格式如何。

这是我的第一个问题:) 抱歉给您带来任何不便!谢谢。

python printf f-string self-healing
1个回答
-1
投票

您面临这个问题是因为您没有使用变量作为参数,而是传递了一个字符串。

简单来说,变量的使用不带引号。

这样就可以解决问题了

prints('Hello? ' + Test)

© www.soinside.com 2019 - 2024. All rights reserved.