如何在 Python 中检查变量是否为字符串

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,你将学习如何在 Python 中检查一个变量是否为字符串。这需要你理解基本的字符串数据类型,并探索识别字符串的方法。

你将首先使用单引号、双引号和三引号(包括多行字符串)来创建和操作字符串。然后,你将学习使用 type() 函数和 isinstance() 函数来确认一个变量是否存储了字符串值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ObjectOrientedProgrammingGroup(["Object-Oriented Programming"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/BasicConceptsGroup -.-> python/strings("Strings") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("Classes and Objects") subgraph Lab Skills python/variables_data_types -.-> lab-559603{{"如何在 Python 中检查变量是否为字符串"}} python/numeric_types -.-> lab-559603{{"如何在 Python 中检查变量是否为字符串"}} python/strings -.-> lab-559603{{"如何在 Python 中检查变量是否为字符串"}} python/booleans -.-> lab-559603{{"如何在 Python 中检查变量是否为字符串"}} python/build_in_functions -.-> lab-559603{{"如何在 Python 中检查变量是否为字符串"}} python/classes_objects -.-> lab-559603{{"如何在 Python 中检查变量是否为字符串"}} end

理解 Python 中的字符串

在这一步中,你将学习 Python 中的字符串。字符串用于表示文本,是编程中最基本的数据类型之一。你将探索如何创建字符串、如何使用它们,以及可以对字符串执行的一些常见操作。

首先,使用 VS Code 编辑器在你的 ~/project 目录下创建一个名为 string_examples.py 的 Python 文件。

可以使用单引号 ('...') 或双引号 ("...") 来创建字符串。让我们在 string_examples.py 中添加一些示例:

## Creating strings
string1 = 'Hello, LabEx!'
string2 = "Python is fun"

print(string1)
print(string2)

保存文件。现在,在终端中使用 python 命令运行这个脚本:

python ~/project/string_examples.py

你应该会看到以下输出:

Hello, LabEx!
Python is fun

字符串还可以包含数字、符号和空格:

string3 = "12345"
string4 = "!@#$%^"
string5 = "This is a sentence."

print(string3)
print(string4)
print(string5)

将这些代码行添加到你的 string_examples.py 文件中,然后再次运行它:

python ~/project/string_examples.py

你应该会看到以下输出:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.

Python 还支持使用三引号 ('''...'''"""...""") 创建多行字符串:

string6 = '''This is a
multi-line string.'''

string7 = """This is another
multi-line string."""

print(string6)
print(string7)

将这些代码行添加到你的 string_examples.py 文件中,然后再次运行它:

python ~/project/string_examples.py

你应该会看到以下输出:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.

理解如何创建和使用字符串对于在 Python 中处理文本数据至关重要。在接下来的步骤中,你将了解更多关于字符串操作以及如何有效地操作字符串的知识。

使用 type() 进行检查

在这一步中,你将学习如何使用 Python 中的 type() 函数来检查变量的数据类型。这是一个了解你所处理的数据类型以及调试代码的有用工具。

让我们继续使用你在上一步中创建的 string_examples.py 文件。我们将添加一些代码来检查我们定义的变量的类型。

type() 函数返回一个对象的类型。例如,如果你有一个字符串变量,type() 将返回 <class 'str'>

在你的 string_examples.py 文件中添加以下代码行:

## Checking the type of variables
print(type(string1))
print(type(string2))
print(type(string3))

保存文件。现在,在终端中使用 python 命令运行脚本:

python ~/project/string_examples.py

你应该会看到以下输出:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>

如你所见,type() 函数确认了 string1string2string3 都是 str 类型,str 代表字符串。

现在,让我们添加一些其他类型的变量,看看 type() 对它们是如何工作的。在你的 string_examples.py 文件中添加以下代码行:

## Checking the type of other variables
number = 10
decimal = 3.14
boolean = True

print(type(number))
print(type(decimal))
print(type(boolean))

保存文件并再次运行:

python ~/project/string_examples.py

你应该会看到以下输出:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

在这里,type() 显示 numberint(整数)类型,decimalfloat(浮点数)类型,booleanbool(布尔值)类型。

在 Python 中,使用 type() 是检查变量数据类型的一种简单方法。当你处理不同类型的数据并需要确保执行正确的操作时,这会很有帮助。

使用 isinstance() 进行确认

在这一步中,你将学习如何使用 Python 中的 isinstance() 函数来检查一个对象是否是某个特定类或类型的实例。这是另一种验证变量数据类型的方法,在处理继承和自定义类时尤其有用。

让我们继续使用你一直在编辑的 string_examples.py 文件。我们将添加一些代码来演示 isinstance() 的工作原理。

isinstance() 函数接受两个参数:你要检查的对象以及你要与之进行比较的类或类型。如果对象是指定类或类型的实例,它将返回 True,否则返回 False

在你的 string_examples.py 文件中添加以下代码行:

## Checking with isinstance()
print(isinstance(string1, str))
print(isinstance(number, int))
print(isinstance(decimal, float))
print(isinstance(boolean, bool))
print(isinstance(string1, int))

保存文件。现在,在终端中使用 python 命令运行脚本:

python ~/project/string_examples.py

你应该会看到以下输出:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
True
True
True
True
False

如你所见,isinstance(string1, str) 返回 True,因为 string1 是一个字符串。同样,isinstance(number, int) 返回 True,因为 number 是一个整数,依此类推。然而,isinstance(string1, int) 返回 False,因为 string1 不是一个整数。

isinstance() 也可以用于自定义类。例如:

class MyClass:
    pass

obj = MyClass()

print(isinstance(obj, MyClass))

将这些代码行添加到你的 string_examples.py 文件中,然后再次运行它:

python ~/project/string_examples.py

你应该会看到以下输出:

Hello, LabEx!
Python is fun
12345
!@#$%^
This is a sentence.
This is a
multi-line string.
This is another
multi-line string.
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
True
True
True
True
False
True

在这里,isinstance(obj, MyClass) 返回 True,因为 objMyClass 的一个实例。

在 Python 中,使用 isinstance() 是检查对象类型的一种强大方法,特别是在处理继承和自定义类时。它使你能够编写更健壮、更灵活的代码,从而正确处理不同类型的数据。

总结

在本次实验中,第一步着重于理解 Python 中的字符串,它是用于表示文本的基础数据类型。这部分内容涵盖了使用单引号、双引号和三引号创建多行字符串的方法。文档还提供了示例,展示了字符串如何包含数字、符号和空格。

本实验指导你创建一个 string_examples.py 文件,添加各种字符串示例,并使用 python 命令执行脚本以观察输出。这种实践方法有助于巩固你对 Python 中字符串创建和操作的理解。