You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中print输出第二行前出现多余空格的问题求助

Python中print输出第二行前出现多余空格的问题求助

嘿,我太懂你现在急得抓耳挠腮的感觉了!其实这个第二行前多空格的问题,根本不是换行符的锅,是Python的print函数默认行为在搞鬼,我给你拆解一下:

你看你写的带问题的代码,都是在同一个print()里传了两个字符串参数对吧?比如这一段:

print('First password: {}\n'.format (first_password),
      'Second password: {}\n'.format(second_password))

Python的print函数默认会用空格(也就是sep参数的默认值' ')把多个传入的参数拼接起来。那你这两个参数,第一个是'First password: Red_Biggie\n',第二个是'Second password: 7Biggie7\n',拼接之后就变成了'First password: Red_Biggie\n Second password: 7Biggie7\n'——这不就刚好对应你输出里第二行前的那个空格嘛!

给你几个马上就能用的修复方案,选哪个都能解决问题:

方案1:把内容合并成一个字符串再打印

不要给print传多个参数,用一个格式化字符串把两行内容都包进去,彻底避开自动加空格的逻辑:

# 用format合并内容
print('First password: {}\nSecond password: {}\n'.format(first_password, second_password))
print('Number of characters in {}: {}\nNumber of characters in {}: {}'.format(first_password, x, second_password, y))

# 如果你的Python版本是3.6+,用f-string更简洁
print(f'First password: {first_password}\nSecond password: {second_password}\n')
print(f'Number of characters in {first_password}: {x}\nNumber of characters in {second_password}: {y}')

方案2:修改print的sep参数为空字符串

直接把print的分隔符设为空,让它不要在参数之间加空格:

print('First password: {}\n'.format(first_password),
      'Second password: {}\n'.format(second_password), sep='')

print('Number of characters in {}: {}\n'.format(first_password, x),
      'Number of characters in {}: {}'.format(second_password, y), sep='')

方案3:分开打印但控制end参数

如果你之前试过分次打印但间距太大,是因为print默认结尾会加换行符。你可以把第一个print的end设为空,让第二个内容紧跟在后面:

print('First password: {}'.format(first_password), end='')
print('\nSecond password: {}\n'.format(second_password))

print('Number of characters in {}: {}'.format(first_password, x), end='')
print('\nNumber of characters in {}: {}'.format(second_password, y))

这几种方法都能快速解决问题,我个人推荐方案1,写法最直观也不容易出错,你可以直接复制替换你的代码试试!

备注:内容来源于stack exchange,提问作者The Trickster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:00:27