user14180335
user14180335

Reputation:

Making the printf function of C into Python

I wanna make a "Hello, (name)." function in Python by trying to make the C printf function.

I want to turn it from this:

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

Into this:

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

I started off the function like this and I knew it wasn't going to work because of the second argument:

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

How can I make a properly working printf function like this?

Upvotes: 1

Views: 834

Answers (4)

suchenguo
suchenguo

Reputation: 4

You don't have to rewrite a function at all. You see:

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

Upvotes: 0

Sam Dani
Sam Dani

Reputation: 124

I think you are expecting something like this:

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

You can learn more here: String Formatting in learnpython.org

Upvotes: 0

Salty Sodiums
Salty Sodiums

Reputation: 318

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

That should do the trick, but perhaps just use an f string like you did in the first example, no need to "reinvent the wheel" right?

Upvotes: 2

SpacedOutKID
SpacedOutKID

Reputation: 155

there is no printf function in Python, there however is the f string. You used it in one of your examples just go with that its honestly super easy and efficient

Upvotes: 0

Related Questions