Python 中在输入消息后添加换行符
使用 \n 字符在输入消息后添加换行符,例如 user_input = input(‘Enter a word:\n’)。 \n 字符将在输入消息后立即添加一个换行符。
user_input = input('Enter a word:\n')
print(user_input)
\n 字符在输入消息后立即添加一个换行符。
然后该函数从输入中读取该行,将其转换为字符串并返回结果。
如果需要将值转换为数字,请使用 int() 类。
user_input = ''
try:
user_input = int(input('Enter an integer\n'))
except ValueError:
print('Invalid integer')
print(user_input)
如果我们将输入消息存储在变量中,请使用加法 + 运算符将换行符附加到消息中。
message = 'Enter a word:'
user_input = input(message + '\n')
print(user_input)
上面的代码片段实现了相同的结果。
我们还可以使用格式化的字符串文字。
message = 'Enter a word:'
user_input = input(f'{message}\n')
print(user_input)
格式化字符串文字 f-strings 让我们通过在字符串前加上 f 来在字符串中包含表达式。
my_str = 'is subscribed:'
my_bool = True
result = f'{my_str} {my_bool}'
print(result) # ?️ is subscribed: True
确保将表达式用大括号括起来 – {expression}。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。