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

Python调用print函数输出出现多余空格,如何让冒号紧邻前面文本

问题原因

Python的print()函数传入多个用逗号分隔的参数时,默认会在所有参数之间自动插入一个空格,你将password1、:作为两个独立参数传入,二者之间就会被自动加上多余空格。

可行修改方案
  • 方案1:使用f-string格式化输出(Python 3.6及以上版本推荐,写法最简洁直观)
print(f'Number of characters in {password1}: {len(password1)}')
print(f'Number of characters in {password2}: {len(password2)}')
  • 方案2:使用字符串拼接手动组装输出内容
    需要注意数值类型要手动转为字符串类型:
print('Number of characters in ' + password1 + ':' + str(len(password1)))
print('Number of characters in ' + password2 + ':' + str(len(password2)))
  • 方案3:修改print()函数的分隔符参数sep
    将默认的空格分隔符改为空字符串,自行控制内容之间的空格:
print('Number of characters in ', password1, ': ', len(password1), sep='')
print('Number of characters in ', password2, ': ', len(password2), sep='')

内容的提问来源于stack exchange,提问作者sherry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:06:07