如何在Python字符串中检查空格?
在当前的21世纪,处理数据是高数据量组织面临的最具挑战的任务,随着数据科学和机器学习的发展,访问数据变得更加容易。空格也被称为字符串字符之间的空白。空格没有数据或者只是空的,这在编程时会导致问题。因此,为了检查字符串中的空格,涉及到许多方法,其中一些在这里解释。
检查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程序
算法
-
Step 1 − 导入re模块并将输入初始化为字符串变量” Welcome to Tutorialspoint”。
-
Step 2 − 字符串中单词之间有空格,使用re.match()方法来检查空格。
-
Step 3 − 基于给定的索引值,找到该索引值处是否存在空格。
-
Step 4 − 索引值从0开始,本代码中索引值7初始化为找到空格的位置。
-
Step 5 − 如果空格存在,则返回“True”,否则返回“False”。
-
Step 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()和正则表达式。删除空格后,程序可以顺利运行。