迹忆客 专注技术分享

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

Python 中如何在的同一行上输入并打印

作者:迹忆客 最近更新:2023/01/07 浏览次数:

将字符串传递给 input() 函数以在同一行上打印语句和输入,例如 username = input('Enter your username: ')input() 函数接受一个提示字符串并将其打印到标准输出而没有尾随换行符。

# ✅ print input message on same line

username = input('Enter your username: ')
print(username)

# ----------------------------------

# ✅ use print() and input() without separator and newline character

print(
  'Your username is: ',
  input('Enter your username: '),
  sep='',
  end=''
)

在第一个示例中,我们将提示字符串传递给了 input() 函数。

Python 中如何在的同一行上输入并打印

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

s = input('Enter your name: ')

print(s)

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

我们还可以在 input() 函数之前或之后使用 print() 函数。

print('this runs before')

user_input = input('Enter your username: ')

print('this runs after')

如果我们使用 print() 函数而不是提示参数,打印语句将打印在单独的一行上。

print('Enter your name: ')

s = input()

print(s)

Python 打印语句将打印在单独的一行上

如果要使用不带分隔符的多个参数调用 print() 函数,请将 sepend 关键字参数设置为空字符串。

print(
  'Your username is: ',
  input('Enter your username: '),
  sep='',
  end=''
)

sep 参数是我们传递给 print() 的参数之间的分隔符。

默认情况下,参数设置为空格。

print('a', 'b', 'c')  # 👉️ 'a b c'

print('a', 'b', 'c', sep='')  # 👉️ 'abc'

end 参数打印在消息的末尾。

默认情况下,结束设置为换行符 \n

print('a', 'b', 'c')  # 👉️ 'a b c\n'

print('a', 'b', 'c', end='')  # 👉️ 'a b c'

我们还可以使用格式化字符串文字在同一行上打印多个参数。

print(f'Your name is: {input("Enter your name: ")}')

格式化字符串文字 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便