如何包装使用格式说明符/占位符的超长字符串



我知道你会很想把它标记为重复,但不同的是我使用的是格式占位符。

原始线路

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

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

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.

试试这个:

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

两次刺痛都需要输入f

您已经完成了大部分工作。您所需要做的就是在打印语句的每一行之前使用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

在要开始下一行的字符串中添加

最新更新