在Python中,用两个加号包围变量称为什么?
当你用加号把一个变量放进字符串里,这种做法叫什么呢?
例子 1:
variable = "stuff"
print "I would like to print "+variable+" "
那这样做和下面这个例子有什么不同呢?
例子 2:
variable = "stuff"
print "I would like to print %s" % variable
我刚开始接触编程和这个网站,请原谅我的无知,如果我有什么不对的地方,请指正我。
相关问题:
2 个回答
1
这个 + 符号其实是一个“重载运算符”。它可以用来做加法,比如你把两个整数相加(1+1),但它也可以用在字符串上。实际上,你不需要在想要“相加”(连接)的字符串两边都使用它,只需要在打印的字符串末尾加一个空格就可以了。
来看几个例子:
print 1 + 1 #this prints 2
str = "a"
print str + "b" #this prints ab
print 1 + "b" #this will error as python doesn't know by default how to "sum" an integer to a string
注意,加两个整数的行为和连接两个字符串是完全不同的。如果你写 "1"+"1",你得到的不是字符串 "2",而是字符串 "11"。这就是重载的意思。
回到你的例子:
variable = "stuff" #this is a string
print "I would like to print "+variable+" "
这里 "I would like to print " 和 " " 都是字符串。你首先创建了第一个字符串,然后把 variable 里的字符串加到它上面。接着你又加了一个字符串,这次是一个只包含“空格”字符的字符串。最后得到的字符串就是要打印的内容。
3
你现在是在连接字符串,而不是在两个+符号之间放东西。可以把这跟加数字比较一下:
4 + 5 + 6
这里的5并没有什么特别的,它只是(4 + 5) + 6的结果。你的表达式其实就是把一个值加到一个字符串上,然后再加上另一个字符串。
你应该尽量使用字符串格式化,因为这样更容易读懂,也更灵活。可以考虑学习一下str.format(),这是一个更一致、更强大的字符串格式化方法:
variable = "stuff"
print "I would like to print {}".format(variable)
mapping = {'answer': 42, 'interest': 0.815}
print '''\
The answer to the ultimate question: {m[answer]:>10d}
Rate: {m[interest]:03.2%}!'''.format(m=mapping)
示例:
>>> variable = "stuff"
>>> print "I would like to print {}".format(variable)
I would like to print stuff
>>> mapping = {'answer': 42, 'interest': 0.815}
>>> print '''\
... The answer to the ultimate question: {m[answer]:>10d}
... Rate: {m[interest]:03.2%}!'''.format(m=mapping)
The answer to the ultimate question: 42
Rate: 81.50%!