문제

I'm new to programming and I stumbled across something unsightly that I would like to remove. Here's my code:

def test1():
    print "What is your name, traveler?"
    name = raw_input()
    print "Hi %r!" % (name)

Here's the output:

What is your name traveler?
Hi 'Karatepig'!

Is there any way to get rid of those single quotes around my name?

도움이 되었습니까?

해결책

You want to use %s there, not %r.

print "Hi %s!" % (name)

I'd add details, but I think others have already written better explanations here and here.

Most saliently:

The difference between %s and %r is that %s uses the str function and %r uses the repr function. You can read about the differences between str and repr in this answer, but for built-in types, the biggest difference in practice is that repr for strings includes quotes and all special characters are escaped.

다른 팁

Or use the "new" string formatting method:

def test1():
print "What is your name, traveler?"
name = raw_input()
print "Hi {0}!".format(name)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top