python中isspace的用法_Python string isspace()用法及代码示例

在Python中,isspace()是用于字符串处理的内置方法。如果字符串中的所有字符均为空格字符,则isspace()方法返回“True”,否则,返回“False”。此函数用于检查参数是否包含所有空格字符,例如:

' ' - 空间

‘\ t’-水平标签

‘\ n’-换行符

‘\ v’-垂直标签

‘\ f’-提要

‘\ r’-回车

用法:

string.isspace()

参数:

isspace() does not take any parameters

返回:

1.True- If all characters in the string are whitespace characters.

2.False- If the string contains 1 or more non-whitespace characters.

例子:

Input:string = 'Geeksforgeeks'

Output:False

Input:string = '\n \n \n'

Output:True

Input:string = 'Geeks\nFor\nGeeks'

Output:False

# Python code for implementation of isspace()

# checking for whitespace characters

string = 'Geeksforgeeks'

print(string.isspace())

# checking if \n is a whitespace character

string = '\n \n \n'

print(string.isspace())

string = 'Geeks\nfor\ngeeks'

print( string.isspace())

输出:

False

True

False

Application

给定python中的字符串,请计算字符串中的空白字符数。

例:

Input:string = 'My name is Ayush'

Output:3

Input:string = 'My name is \n\n\n\n\nAyush'

Output:8

算法

1.逐字符遍历给定的字符串字符直至其长度,检查字符是否为空格字符。

2.如果是空格字符,则将计数器加1,否则遍历下一个字符。

3.打印计数器的值。

# Python implementation to count whitespace characters in a string

# Given string

# Initialising the counter to 0

string = 'My name is Ayush'

count=0

# Iterating the string and checking for whitespace characters

# Incrementing the counter if a whitespace character is found

# Finally printing the count

for a in string:

if (a.isspace()) == True:

count+=1

print(count)

string = 'My name is \n\n\n\n\nAyush'

count = 0

for a in string:

if (a.isspace()) == True:

count+=1

print(count)

输出:

3

8

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值