使用变量和替换的Python约定

2024-09-24 00:29:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读http://interactivepython.org/courselib/static/pythonds/Introduction/introduction.html#review-of-basic-python的第一章。为什么是:

print("%s is %d years old." % (aName, age))

(即使用格式化字符串)作为惯例,优先于直接在句子中使用变量,即:

print(aName, "is", age, "years old.")

什么?你知道吗


Tags: orghttpageishtmlstaticoldintroduction
2条回答

使用格式化的字符串版本是一个好习惯。你知道吗

通常它们读起来更清晰,但对我来说最重要的是,它使internationalization and localization成为可能。你知道吗

更好的是,使用关键字/mapping版本。例如

print "{name} is {age} years old.".format(name=aName, age=age)

自动化工具可以更好地扫描程序中的这些字符串,以创建翻译所需的“.po”文件。你知道吗

我通常只是使用逗号版本,如果我正在做一些快速,只是想打印一堆数字或类似的。你知道吗

如前所述str.format格式现在是推荐的方法。根据我个人的经验,'%s'(str)有一个错误的例子是sql语句。。。你知道吗

q = "select * from table where colName like '%string%' and colName2 = %s"
conn.cursor.execute(q%'screwsUp')

上面的方法行不通 但下面有

q = "select * from table where colName like '%string%' and colName2 = {0}" 
conn.cursor.execute(q.format('works'))

当你想插入字典值时,格式也更性感。。。你知道吗

d = {"first":"ronald","last":"McDonald"}
print "Name's {0[last]}... {0[first]} {0[last]}".format(d)

相关问题 更多 >