繁体   English   中英

将C的printf函数变成Python

[英]Making the printf function of C into Python

我想做一个“你好,(名字)”。 通过尝试使 C printf函数在 Python 中起作用。

我想把它从这个:

name = input("What's your name? ")
print(f"Hello, {name}.")

进入这个:

name = input("What's your name? ")
printf("Hello, %s.", name)

我开始这样的功能,我知道它不会工作,因为第二个参数:

def printf(text, ...):
    print(text)

如何制作这样一个正常工作的 printf 函数?

def printf(text, *args):
    print(text % args)

这应该可以解决问题,但也许就像在第一个示例中一样使用 f 字符串,无需“重新发明轮子”,对吗?

Python 中没有 printf 函数,但是有 f 字符串。 你在你的一个例子中使用了它,它真的超级简单和高效

我想你正在期待这样的事情:

name = input("What's your name?")
print("Hello, %s!" % name)

您可以在此处了解更多信息: learnpython.org 中的字符串格式

您根本不必重写函数。 你看:

name = input("What's your name? ")
print("Hello,%s."%name) # Basically the same as the printf function.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM