如何在 Python 字符串中检查空格?
在当今的 21 世纪,对于拥有大量数据的组织来说,处理数据是最具挑战性的任务,并且随着数据科学和机器学习的发展,数据访问变得更加容易。空格也称为字符串字符之间的空白字符。空格没有数据,或者它只是空的,并且在程序员编码时会造成问题。因此,为了检查字符串中的空格,涉及多种方法,这里解释了一些方法。字符串由字符组成,Python 语言属于 OOPS 概念,它会立即运行代码而无需检查错误。
如何在 Python 字符串中检查空格
在字符串数据结构中,可以使用以下各种方法或方法来检查空格:
方法
方法 1:使用 isspace() 方法
方法 2:使用正则表达式
方法 3:使用“in”运算符
方法 1:使用 isspace() 方法检查字符串中空格的 Python 程序
isspace() 方法检查给定字符串中的空白字符,并提及索引值以检查空格。
算法
步骤 1 − 初始化名为 check_sent 的变量。
步骤 2 − 字符串在单词之间包含空格,要检查空格,使用 isspace() 方法。
步骤 3 − 它根据索引值验证该索引值处是否存在空格。
步骤 4 − 索引值从 0 开始,在此代码中,索引值 7 被初始化以搜索空格。
步骤 5 − 如果存在空格,则返回“True”,否则返回“False”。
步骤 6 − 基于空格,返回相应的语句。
示例
#initializing the string with a sentence and assigning it to a variable
check_sent = "Welcome to Tutorialspoint"
#isspace() method is used to check whether the space is found in index value of 7
if check_sent[7].isspace():
#if true this statement is printed
print("The string contains whitespaces")
else:
#if false this statement is printed
print("The string does not contain whitespaces")
输出
The string contains whitespaces
方法 2:使用正则表达式检查字符串中空格的 Python 程序
算法
步骤 1 − 导入 re 模块,并将输入初始化为字符串变量“ Welcome to Tutorialspoint”。
步骤 2 − 字符串在单词之间包含空格,要检查空格,使用 re.match() 方法。
步骤 3 − 根据给定的索引值,它查找该索引值处是否存在空格。
步骤 4 − 索引值从 0 开始,在此代码中,索引值 7 被初始化以查找空格。
步骤 5 − 如果存在空格,则返回“True”,否则返回“False”。
步骤 6 − 最后,打印指定的语句。
示例
#importing the re module
import re
# initializing the string with a sentence and assigning it to a variable
check_sent = "Welcome to Tutorialspoint"
# using regular expressions to check if there is whitespace at index 7
if re.match(r"\s", check_sent[7]):
#if true this statement is printed
print("The string contains whitespace")
else:
#if false this statement is printed
print("The string does not contain whitespace")
输出
The string contains whitespaces
方法 3:使用“in”运算符检查字符串中空格的 Python 程序
声明“in”运算符,并基于此声明,在给定字符串中检查空格。
算法
步骤 1 − 初始化输入字符串并分配变量。
步骤 2 − 字符串在单词之间包含空格,要检查空格,使用“in”运算符。
步骤 3 − 根据给定的索引值,它查找该索引值处是否存在空格。
步骤 4 − 索引值从 0 开始,在此代码中,索引值 7 被初始化以查找空格。
步骤 5 − 如果存在空格,则返回“True”,否则返回“False”。
步骤 6 − 基于空格,返回相应的语句。
示例
# initializing the string with a sentence and assigning it to a variable
check_sent = "Welcome to Tutorialspoint"
# using the 'in' operator to check if there is whitespace at index 7
if ' ' in check_sent[7]:
# if true this statement is printed
print("The string contains whitespaces")
else:
# if false this statement is printed
print("The string does not contain whitespaces")
输出
The string does not contain whitespaces
结论
Python 程序用于检查给定数据结构中的空格或空白字符。要检查 Python 字符串中的空格,我们可以使用各种方法,例如“in”运算符、isspace() 以及正则表达式。删除空格后,程序可以顺利运行。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP