首页 > 文章列表 > 如何在Python中从用户输入一个字符串?

如何在Python中从用户输入一个字符串?

Python 字符串 用户输入
369 2023-08-22

在Python中,有几种方法可以从用户输入一个字符串。最常见的方法是使用内置函数input()。该函数允许用户输入一个字符串,然后将其存储为一个变量以供程序使用。

示例

下面是一个在Python中从用户输入字符串的示例−

# Define a variable to store the input
name = input("Please enter your name: ")
# Print the input
print("Hello, " + name + "! Good to see you.")

输出

上述代码为我们生成了以下输出

Please enter your name: Max
Hello, Max! Good to see you.

在上面的代码中,我们有:

  • 定义一个变量来存储输入 − name = input("请输入您的姓名:")

    • 在这一步中,创建了一个名为"name"的变量,用于存储用户输入。

  • 提示用户输入他们的名字 − input("请输入您的名字:")

    • "input()"函数用于向用户显示一条消息,要求他们输入他们的姓名。消息“请输入您的姓名:”作为参数传递给函数。

  • 将用户的输入存储在"name"变量中 − name = ...

    • “input()”函数调用的结果存储在“name”变量中。这意味着用户的输入现在存储在“name”变量中,可以随时使用。

  • 打印输入 − print("你好," + name + "!很高兴见到你。")

    • In this step, the "print()" function is used to display a message to the user, using the value stored in the "name" variable. The message, "Hello, [name]! Good to see you.", is passed as an argument to the function. The value of "name" is concatenated with the rest of the string using the "+" operator.

记住,"input()"函数的输出始终是一个字符串,即使用户输入的是一个数字。如果您需要将输入作为数字使用,您需要将其转换为相应的数据类型(例如int或float)。

示例

这是一个从用户输入数字的示例 -

# Define a variable to store the input
age = int(input("Please enter your age: "))
# Print the input
print("Wow, you are " + str(age) + " years old!")

输出

上述代码为我们生成了以下输出

Please enter your age: 24
Wow, you are 24 years old!

从上面的代码中,

  • 创建一个名为"age"的变量,用于存储用户的输入。

  • 将消息“请输入您的年龄:”作为参数传递给函数。

  • 由于“input()”函数始终返回一个字符串,我们需要使用“int()”函数将用户的输入转换为整数。这样可以将用户的输入存储为数字,而不是字符串。

  • 将"int()"函数调用的结果存储在"age"变量中。

  • “print()”函数用于显示一条消息给用户,使用存储在“age”变量中的值。消息“哇,你今年[age]岁了!”作为参数传递给函数。使用“str()”函数将“age”的值首先转换为字符串,然后使用“+”运算符与其余的字符串连接。

也可以为输入框指定一个默认值,以防用户没有提供任何输入。可以使用"or"运算符和默认值来实现这一点 −

示例

# Define a variable to store the input
name = input("Please enter your name (or press enter for default): ") or "Max"
# Print the input
print("Hello, " + name + "! Good to see you.")

输出

上述代码为我们生成以下输出

Please enter your name (or press enter for default): 
Hello, Max! Good to see you.

在上面的代码中,

  • 创建一个名为 "name" 的变量,用于存储用户输入的名称。

  • 将消息“请输入您的姓名(或按回车键使用默认值)−”作为参数传递给函数。

  • or 运算符用于为 name 变量设置默认值。如果用户在未输入名称的情况下按下回车键,input() 函数将返回一个空字符串。如果用户的输入是空字符串,则 or 运算符将计算为默认值 "Max"。

  • 将input()函数调用的结果,或默认值"Max"存储在name变量中。

  • 使用name变量打印个性化问候。使用+运算符来连接字符串值,创建一个要打印的单个字符串。

结论

总结一下,在Python中从用户那里接收一个字符串是一个简单的任务,可以通过使用现成的"input()"方法来完成。无论您需要收集一个字符串还是一个数值,将输入转换为适当的数据类型并将其保存在变量中以供将来参考都是轻而易举的。

"input()"方法是从用户获取信息并将其存储以供以后在代码中使用的方便工具。