Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
774 views
in Technique[技术] by (71.8m points)

python - TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

So I am VERY new to programming and I started with Python 3. I started reading "Learn Python the Hard Way". Now, I got to a point where I had this code:

x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s" % (binary, do_not)

print(x)
print(y)
print("I said: %r") % x

I do not really know the difference between %r, %s and %d. The error I get is TypeError: unsupported operand type(s) for %: 'NoneType' and 'str' No idea what to do and how to fix it. Please explain how I can actually make it work and why it won't work. Also, what is the difference between %r,d and s? Any useful links? Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to apply % to the string instead:

print("I said: %r" % x)

Your code is applying it to the return value of the print() call, which returns None.

Alternatively, you can switch to using str.format():

print("I said: {!r}".format(x))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...