具有字符串连接和延续的 Python str.format

标签 python string format concatenation continuation

我想指定一个包含行继续符和连接符的字符串。如果我要回应一堆相关值,这真的很有用。这是一个只有两个参数的简单示例:

temp = "here is\n"\
    +"\t{}\n"\
    +"\t{}".format("foo","bar")
print(temp)

这是我得到的:

here is
    {}
    foo

这是我所期望的:

here is
    foo
    bar

什么给了?

最佳答案

你可以尝试这样的事情:

temp = ("here is\n"
        "\t{}\n"
        "\t{}".format("foo","bar"))
print(temp)

或者喜欢:

# the \t have been replaced with
# 4 spaces just as an example
temp = '''here is
    {}
    {}'''.format

print(temp('foo', 'bar'))

对比你有什么:

a = "here is\n"
b = "\t{}\n"
c = "\t{}".format("foo","bar")
print( a + b + c)

关于具有字符串连接和延续的 Python str.format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48508171/

相关文章:

python - 从父目录的子目录导入 python 模块

c# - 如何删除换行符以外的控制字符? (C#)

regex - 使用 C++ RegEx 进行后视的替代方法是什么?

java - 数据格式和文件格式 Java 声音

python - 来自守护进程 : OCI runtime create failed: container_linux. 的错误响应 go:380:启动容器进程导致:exec: "python":

python - 在 Pygame 中删除图像周围的边框

python - 两个字符串列表的交集

java - 从一个大字符串中一次读取一个字符

mysql - 我可以将哪些类型的文件格式导入 MySQL Workbench?

Python .format() 使用 class.__dict__ 时出现 KeyError