首页 > 解决方案 > 如何包装使用格式说明符/占位符的很长的字符串?

问题描述

我知道您会很想将其标记为重复,但不同之处在于我使用的是格式占位符。

原线

print(f"There are {rangeSegment} numbers between {rangeStart} and {rangeEnd} inclusively blah blah blah.")

使用接受的 PEP8 建议和 StackOverflow 上接受的答案建议使用隐含连接,但这会产生带有选项卡字符的输出。

print(f"There are {rangeSegment} numbers between {rangeStart} and " \
    "{rangeEnd} inclusively.")

输出

There are 10 numbers between 1 and     10 inclusively.

并尝试拆分多个引号会破坏字符串格式。

print(f"There are {rangeSegment} numbers between {rangeStart} and" \
    "{rangeEnd} inclusively.")

输出

There are 10 numbers between 1 and {rangeEnd} inclusively.

标签: python

解决方案


你有大部分工作。您需要做的就是f在打印语句中的每一行之前使用。

rangeSegment = 20
rangeStart = 2
rangeEnd = 15

print(f"There are {rangeSegment} numbers between {rangeStart} and " \
      f"{rangeEnd} inclusively.") \
      f" I am going to have another line here {rangeStart} and {rangeEnd}." \
      f" One last line just to show that i can print more lines.")

上面的语句将打印以下内容:

There are 20 numbers between 2 and 15 inclusively. I am going to have another line here 30 and 40. One last line just to show that i can print more lines.

请注意,如果您想打破两者之间的界限,那么您必须使用\n您认为想要打破的任何地方。

例如,如果您的打印语句如下:

print(f"There are {rangeSegment} numbers between {rangeStart} and " \
    f"{rangeEnd} inclusively.\n"  \
    f"I am going to have another line here {rangeStart} and {rangeEnd}\n" \
    f"One last line just to show that i can print more lines")

然后,您的输出将如下所示。将\n创建新行。

There are 20 numbers between 30 and 40 inclusively.
I am going to have another line here 30 and 40
One last line just to show that i can print more lines

推荐阅读