[英]Python Block Formatting
如何在字符串格式化的上下文中縮進多行字符串? 例如
'''
<
%s
>
''' % (paragraph)
其中段落包含換行符。 ( '富\\ NBAR')
如果我使用上面的代碼,我得到這樣的輸出:
'''
<
foo
bar
>
'''
當我真的想要這個:
'''
<
foo
bar
>
'''
我知道我可以這樣做:
'''
<
%s
>
''' % (paragraph)
但這會破壞我的目的的可讀性。
我也意識到我可以寫一些代碼來縮進除了第一行之外的所有縮進,但是這不是一個可擴展的解決方案(如果我有2個縮進?或3?等等)
編輯 :在您發布答案之前,請考慮您的解決方案如何使用以下內容:
'''
<
%s
<
%s
%s
<
%s
>
>
>
''' % (p1, p2, p3, p4)
這個怎么樣:
'''
<
%s
>
''' % ("\n ".join(paragraph.split("\n")))
結果:
<
foo
bar
>
.join()
方法中使用的字符串必須包含相同的空格(加上開頭的\\n
),就像字符串中%s
之前的字符串一樣。
你不能指望Python解釋器自動縮進你的paragraph
。 您是否希望口譯員弄亂您的數據? (提示:沒有。)
你能做的就是注入空白:
'''
<
%s
>
''' % (paragraph.replace('\n','\n ')) # assuming 4 space soft tabs
但是除非你絕對不得不這樣做,否則我會非常謹慎,因為你不知道你可能會處理哪些行結尾,並且通常感覺有點尷尬。
Python的textwrap模塊是你的朋友,特別是它的initial_indent
和subsequent_indent
參數。
好的,簡單不適合你的目的。 您需要使用文檔對象模型和具有適當縮進的展平系統。
或者,你可以做一些相當hacky來檢測每次替換之前的空白量。 這很脆弱:
import re
def ind_sbt(text,indent='\t'):
return text.replace('\n','\n%s' % (indent,))
def adjust_indents(fmtstr,*args):
"""Hacky, crude detection of identation level"""
indented_substitutions = re.compile(r'\n(\s+)%s')
return fmtstr % tuple([ ind_sbt(arg,indent=i) for (arg,i) in zip(args,indented_substitutions.findall(fmtstr))])
p1 = p2 = p3 = p4 = "foo\nbar"
print adjust_indents('''
<
%s
<
%s
%s
<
%s
>
>
>
''',p1,p2,p3,p4)
產量:
<
foo
bar
<
foo
bar
foo
bar
<
foo
bar
>
>
>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.