Python judges whether a string is all empty characters - usage and examples of the isspace function

Table of contents

1. The syntax and usage of the isspace function

①Syntax: string.isspace()

②Usage: Determine whether the string contains only null characters.

2. Instance of isspace

(1) Simple usage

(2) Used in conjunction with the if conditional function

(3) Combined use with input function and if conditional function

(3) Combined use with for traversal function and if conditional function


1. The syntax and usage of the isspace function

①Syntax: string.isspace()

②Usage: Determine whether the string contains only null characters.

Return two necessary conditions for True

①The string contains at least one character

②The string is a null character, and the null character can be a space (' '), a horizontal tab ('\t'), a carriage return ('\r'), a line feed ('\n'), or a page feed ('\f') etc.

In other cases, the return result is False


2. Instance of isspace

(1) Simple usage

"""isspace函数"""
"".isspace()
#输出结果为False 解释:因为该字符串没有字符所以返回为False

' '.isspace()
#输出结果为True 解释:因为该字符串只有空格字符' '字符所以返回为True

'\n'.isspace()
#输出结果为True 解释:因为该字符串只有换行符'\n'所以返回为True 

'\t'.isspace()
#输出结果为True 解释:因为该字符串只有横向制表符'\t'所以返回为True 

'\r'.isspace()
#输出结果为True 解释:因为该字符串只有回车符'\r'所以返回为True 

'\f'.isspace()
#输出结果为True 解释:因为该字符串只有换页符'\f'所以返回为True 

'\f\r\t '.isspace()
#输出结果为True 解释:因为该字符串只有多种空字符'\f\r\t '所以返回为True 

(2) Used in conjunction with the if conditional function

Determine whether a string contains only null characters, if yes, return bingo, otherwise return rejectedly.

str = '    '
if str.isspace() is True:
    print('bingo')
else:
    print('dejectedly')

#输出结果为dejectedly

(3) Combined use with input function and if conditional function

Determine whether an input string contains only null characters, if yes, return bingo, otherwise return rejectedly.

str = input('请输入目标字符串')
if str.isspace() is True:
    print('bingo')
else:
    print('dejectedly')


#若输入的值为:     #空字符
#输出结果为:bingo
#若输入的值为:\f\r\t 
#输出结果为:bingo
#若输入的值为:hjk
#输出结果为:dejectedly

(3) Combined use with for traversal function and if conditional function

Determine whether several strings in a list contain only null characters, if yes, return bingo, otherwise return rejectedly.

#定义str
list = [' ','\f','\f\n','hjka ']
for str in list:
    if str.isspace() is True:
        print('bingo')
    else:
        print('dejectedly')

#输出结果为:bingo
#bingo
#bingo
#dejectedly

For specific input function usage, please refer to the article: python's input function usage

For specific usage of if judgment statement, please refer to: usage and examples of if conditional statement in python

Guess you like

Origin blog.csdn.net/weixin_50853979/article/details/126354498