Python 字符串格式和 UUID

Python string formatting and UUID

我正在尝试读取 CSV 数据并将其映射到以下 XML 结构。在我的第一次尝试中,我使用 % 运算符进行字符串格式化,这很有效。

import pandas as pd
import uuid
df = pd.read_csv('media.csv', sep=',')
def convert_row(row):
   return """<video>
    <videoType fileUID="%s" name="">
        <locationType></locationType>
        <type>%s</type>
        <format>%s</format>
        <year>%s</year>
    </videoType>
</video>""" % (row[0], row[1], row[2], row[3])


print '\n'.join(df.apply(convert_row, axis=1))

但是,我希望用生成的 uuid 填充 fileUID="%s",然后我可以在其他地方引用它。我无法让它工作。

我尝试在 return 语句之前添加 u = str(uuid.uuid4()) 并更新 % (u, row[0], row[1], row[2], row[3])

我收到 'not all arguments converted during string formatting' 错误

所以我尝试使用 f 字符串格式

import pandas as pd
import uuid
df = pd.read_csv('media.csv', sep=',')
def convert_row(row):
   return f"""<video>
    <videoType fileUID="{u}" name="">
        <locationType></locationType>
        <type>{row[0]}</type>
        <format>{row[1]}</format>
        <year>{row[2]}</year>
    </videoType>
</video>"""


print '\n'.join(df.apply(convert_row, axis=1))

并收到另一个错误,指出与关闭 """

相关的无效语法

我想我的问题是在处理 UUID 时哪种字符串格式样式是最佳选择以及我的代码有什么问题?另外,如果我想在其他生成的 xml 结构中引用生成的 uuid - 我最终会创建一个 xml 文件,其中包含多个生成的 xml 结构内容。

感谢您的帮助

对于@deceze 的观点,您在显示的代码中缺少一些格式。

我相信你正在寻找这样的东西?

代码

"""UUID Example."""
import pandas as pd
import uuid

df = pd.read_csv('media.csv', sep=',')


def convert_row(row):
    """Convert Row Example."""
    u = str(uuid.uuid4())
    return """<video>
    <videoType fileUID={} name=\"\">
        <locationType></locationType>
        <type>{}</type>
        <format>{}</format>
        <year>{}</year>
    </videoType>
</video>""".format(u, row[0], row[1], row[2], row[3])

print("\n".join(df.apply(convert_row, axis=1)))

结果

$ python3 uuid_testing.py 
<video>
    <videoType fileUID=d07ea048-a08f-444c-9182-7fff3a825dcc name="">
        <locationType></locationType>
        <type>2</type>
        <format>b</format>
        <year>f</year>
    </videoType>
</video>
<video>
    <videoType fileUID=4b058e99-457e-4b26-ac03-593c51e6cb1e name="">
        <locationType></locationType>
        <type>3</type>
        <format>c</format>
        <year>g</year>
    </videoType>
</video>
<video>
    <videoType fileUID=8d04f6e6-1b5b-4103-a42a-aaa9c45d7bc5 name="">
        <locationType></locationType>
        <type>4</type>
        <format>d</format>
        <year>h</year>
    </videoType>
</video>

Github: Code was added to my Repo.