如何在没有缩进的情况下将多行字符串变量打印到控制台?
目前我尝试了这个没有成功:
# Grid.
grid = """rnbqkbnr
pppppppp
********
********
********
PPPPPPPP
RNBQKBNR"""
# Show grid.
print(grid)
输出如下:
rnbqkbnr
pppppppp
********
********
********
PPPPPPPP
RNBQKBNR
这是我要找的输出:
rnbqkbnr
pppppppp
********
********
********
PPPPPPPP
RNBQKBNR
答案 0 :(得分:4)
String s;
//doing something with s will throw NullPointerException
答案 1 :(得分:3)
print('\n'.join(grid.split()))
如果你想要保留你的行中的内部空格:
for line in grid.splitlines():
print(line.strip())
答案 2 :(得分:3)
试试这个:
# Grid.
grid = """\
rnbqkbnr
pppppppp
********
********
********
PPPPPPPP
RNBQKBNR"""
# Show grid.
print(grid)
将\
放在一行的末尾会删除不必要的换行符。
答案 3 :(得分:1)
只是不要在"""
内缩进:
# Grid.
grid = """rnbqkbnr
pppppppp
********
********
********
PPPPPPPP
RNBQKBNR"""
# Show grid.
print(grid)
按预期工作。
答案 4 :(得分:1)
def unindent(string):
return ''.join(map(str.lstrip, string.splitlines(1)))
# Grid.
grid = """rnbqkbnr
pppppppp
********
********
********
PPPPPPPP
RNBQKBNR"""
# Show grid.
print(unindent(grid))
答案 5 :(得分:0)
还可以尝试re
模块并删除所有行的前导空格:
grid = """rnbqkbnr
pppppppp
********
********
********
PPPPPPPP
RNBQKBNR"""
import re
print(re.sub('^\s+', '', grid, flags=re.MULTILINE))
rnbqkbnr
pppppppp
********
********
********
PPPPPPPP
RNBQKBNR