迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中在输入消息后添加换行符

作者:迹忆客 最近更新:2022/12/17 浏览次数:

使用 \n 字符在输入消息后添加换行符,例如 user_input = input('Enter a word:\n')\n 字符将在输入消息后立即添加一个换行符。

user_input = input('Enter a word:\n')

print(user_input)

Python 中在输入消息后添加换行符

\n 字符在输入消息后立即添加一个换行符。

输入函数采用可选的prompt参数并将其写入标准输出而没有尾随换行符。

然后该函数从输入中读取该行,将其转换为字符串并返回结果。

请注意 ,即使用户输入数字,input() 函数也保证返回一个字符串。

如果需要将值转换为数字,请使用 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}

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便