簡體   English   中英

對字符串使用 locals() 和 format() 方法:有什么注意事項嗎?

[英]Using locals() and format() method for strings: are there any caveats?

使用以下模式是否有任何缺點、警告或不良做法警告?

def buildString(user, name = 'john', age=22):
    userId = user.getUserId()
    return "Name: {name}, age: {age}, userid:{userId}".format(**locals())

我有一個非常重復的字符串生成代碼要編寫並且很想使用它,但是使用locals()一些事情讓我感到不舒服。 這是否有任何意外行為的危險?

編輯:上下文

我發現自己一直在寫這樣的東西:

"{name} {age} {userId} {etc}...".format(name=name, age=age, userId=userId, etc=etc)

從 Python 3.6.0 開始,現在有一種官方方法可以做到這一點: 格式化字符串文字

它是這樣工作的:

f'normal string text {local_variable_name}'

例如,而不是這些:

"hello %(name) you are %(age) years old" % locals()
"hello {name} you are {age} years old".format(**locals())
"hello {name} you are {age} years old".format(name=name, age=age)

只需這樣做:

f"hello {name} you are {age} years old"

這是官方的例子:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'

參考:

如果格式字符串不是用戶提供的,這種用法是可以的。

format優於使用舊的%進行字符串替換。
locals是 Python 內置的,它的行為是可靠的。

我認為locals正是您所需要的。
只是不要修改當地人的字典,我會說你有一個很好的解決方案。

如果格式字符串是用戶提供的,您很容易受到各種惡意的注入攻擊。

Python 3.6 之前的答案

這已經很老了,但是如果您發現自己使用.format ,我在傳入**locals遇到的一個警告是,如果您沒有在任何地方定義該變量,它就會中斷。 明確說明傳入的變量將在大多數現代 IDE 中避免這種情況。

foo = "bar"
"{foo} and {baz} are pair programming".format(**locals())
<exception occurs>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM