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
相关产品推荐
相关产品推荐

