我有一本字典:
page_info = {'LISTS':['string 1', 'string 2']}
Run Code Online (Sandbox Code Playgroud)
我想打印到一个文本文件,其中“LISTS”一词作为标题,键的值出现在其下方,并向右缩进一个空格。
with codecs.open(stats_file, 'a', encoding="utf8") as file:
file.write('LISTS:' + '\n')
for tag in page_info['LISTS']:
file.write('\t' + tag + '\n\n')
Run Code Online (Sandbox Code Playgroud)
如您所见,每个字符串仅缩进第一行。如何缩进字符串的整个文本块?
使用该textwrap模块换行并为每行添加缩进:
wrapper = textwrap.TextWrapper(initial_indent='\t', subsequent_indent='\t')
for tag in page_info['LISTS']:
wrapped = wrapper.fill(tag)
file.write(wrapped + '\n')
Run Code Online (Sandbox Code Playgroud)
您可能还想指定一个width参数;默认设置为 70 个字符。