Python 中如何在的同一行上输入并打印
将字符串传递给 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()
函数。
输入函数采用可选的提示参数并将其写入标准输出而没有尾随换行符。
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)
如果要使用不带分隔符的多个参数调用 print()
函数,请将 sep 和 end 关键字参数设置为空字符串。
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}
。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。