在python中打印文本和变量时如何去掉空格 [英] How to get rid of spaces when printing text and variables in python
本文介绍了在python中打印文本和变量时如何去掉空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想让用户输入他的姓名/年龄,然后输出十年后的姓名和年龄.我是这样设置的:
print("让我们看看你 10 年后的年龄.\n")name = input("姓名:")print("\n现在输入你的年龄,",name,"\n")年龄 = 整数(输入(年龄:"))年龄 = 年龄 + 10打印(\n",姓名,你会",ageinten,十年后.")input("按回车键关闭")
输出是这样的:
让我们看看你 10 年后的年龄.名称:示例现在输入您的年龄,例如年龄:20例如,十年后您将 30 岁.按 Enter 关闭
但我希望它没有示例前的空格:
例如,十年后您将 30 岁.按 Enter 关闭
有人可以帮忙解决这个问题吗?
解决方案
更好地使用 字符串格式:
print('\n{} 你将在十年后成为 {}.'.format(name, ageinten))
或使用 sep=''
,但是您必须在字符串中添加尾随和前导空格.:
print("\n", name, " you will be ", ageinten, " in十年.", sep='')
sep
的默认值是一个空格,这就是为什么你得到一个空格.
演示:
<预><代码>>>>名称 = '示例'>>>年龄='20'>>>print("\n",name," 十年后你将成为 ",ageinten,", sep='')例如,十年后您将 20 岁.>>>print('\n{} 你将在十年后成为 {}.'.format(name, ageinten))例如,十年后您将 20 岁.I want to make it so the user enters his name/age and it outputs the name and age in ten years. I have set it out like this:
print("Let's find out how old you will be in 10 Years.\n")
name = input("name: ")
print("\nNow enter your age,",name,"\n")
age = int(input("age: "))
ageinten = age + 10
print("\n",name,"you will be",ageinten,"in ten years.")
input("Press Enter to close")
The output is like this:
Let's find out how old you will be in 10 Years.
name: Example
Now enter your age, Example
age: 20
Example you will be 30 in ten years.
Press Enter to close
But I want it without the space before example:
Example you will be 30 in ten years.
Press Enter to close
Can anyone help with this problem?
解决方案
Better use string formatting:
print('\n{} you will be {} in ten years.'.format(name, ageinten))
or use sep=''
, but then you'd have to add trailing and leading spaces to the strings.:
print("\n", name, " you will be ", ageinten, " in ten years.", sep='')
Default value of sep
is a space, that's why you're getting a space.
Demo:
>>> name = 'Example'
>>> ageinten = '20'
>>> print("\n",name," you will be ",ageinten," in ten years.", sep='')
Example you will be 20 in ten years.
>>> print('\n{} you will be {} in ten years.'.format(name, ageinten))
Example you will be 20 in ten years.
这篇关于在python中打印文本和变量时如何去掉空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文