Python 3: using %s and .format()

家住魔仙堡 提交于 2019-12-03 04:32:44
Vlad

Python 3.2 documentation said that, % will eventually go away.

http://docs.python.org/3.2/tutorial/inputoutput.html#old-string-formatting

Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.

But as @regilero says, the sentence is gone from 3.3, which might suggest it's not actually the case. There are some conversations here that suggest the same thing.

As of Python 3.4 the paragraph 7.1.1 reads:

The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation.

See also Python 3.4 4.7.2 printf-style String Formatting.

"%s" is now "{}", so insted of adding %s replace it with {} where you would want to add the variable into the string.

def main():
    n="Python 3.+" 
    l="looks nice"
    f="does not look practical."


    print("This seems to be the new way {}".format(n)\
      + "will be working, rather than the ' % ',{} but {}".format(l,f))



main()

#In comparison to just injecting the variable

Output disregard the quotes they are for illustration reasons

"This seems to be the new way "Python 3.+" will be working, rather than the '%;, "looks nice" but "does not look practical.""

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!