Python - string formatting: % vs. .format

柔光的暖阳◎ 2022-05-29 06:23 272阅读 0赞

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

.format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You’d think the following would always work:

  1. "hi there %s" % name

yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you’d need to do

  1. "hi there %s" % (name,) # supply the single argument as a single-item tuple

which is just ugly. .format doesn’t have those issues. Also .format is much cleaner looking.

发表评论

表情:
评论列表 (有 0 条评论,272人围观)

还没有评论,来说两句吧...

相关阅读