簡體   English   中英

理解 python 列表理解中的字符串變量替換

[英]Understanding string variable substitution in a python list comprehension

我不確定 Python Cookbook 中列表理解示例中使用的語法。

代碼(包含我的打印語句)如下:

import html

# to accept any number of KEYWORD arguments, use **
# treat the argument as a dictionary
def make_element(name, value, **attrs):
    print(f"attrs has type {type(attrs)}")
    print(f"attrs -> {attrs}")
    print(f"attrs.items() -> {attrs.items()}")
    
    keyvals = ['%s = "%s"' % item for item in attrs.items()]
    
    print(f"keyvals -> {keyvals}")
    
    attr_str = ' '.join(keyvals)
    
    print(f"attr_str -> {attr_str}")
    
    element=f"<{name}{attr_str}>{html.escape(value)}</{name}>"
    
    print(f"element -> {element}")
    
    return element

對我來說令人困惑的是:

keyvals = ['%s = "%s"' % item for item in attrs.items()]

我真的不明白這是在做什么(我得到了輸出),但是 %s = '%s' 和 'item' 關鍵字之前的 % 是我以前沒見過的嗎?

該函數返回:

# method call
make_element('item', 'Albatross', size="Large", color="Blue")

# output
attrs has type <class 'dict'>
attrs -> {'size': 'Large', 'color': 'Blue'}
attrs.items() -> dict_items([('size', 'Large'), ('color', 'Blue')])
keyvals -> ['size = "Large"', 'color = "Blue"']
attr_str -> size = "Large" color = "Blue"
element -> <itemsize = "Large" color = "Blue">Albatross</item>
'<itemsize = "Large" color = "Blue">Albatross</item>'

當應用於字符串(作為左參數)時, %運算符執行 C 樣式的格式替換,生成字符串作為結果。 例如, %s進行字符串格式化, %d進行整數格式化等。

這里有幾個簡單的例子:

>>> '%s' % 'foo'
'foo'
>>> 

>>> '%d' % 123
'123'
>>> 

您可以通過將值打包到一個tuple中來格式化多個值:

>>> '%s %s' % ("foo", "bar")
'foo bar'
>>> 

>>> '%s %d' % ("foo", 123)
'foo 123'
>>> 

最后一個示例基本上就是您的代碼中的情況。 嘗試以下操作:

>>> items = ('foo', 'xyz')
>>> '%s = "%s"' % items
'foo = "xyz"'
>>> 

暫無
暫無

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

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