python strip函数用法_Python string strip()用法及代码示例

strip()是Python编程语言中的内置函数,该函数返回删除了前导和尾随字符的字符串的副本(基于传递的字符串参数)。

用法:

string.strip([chars])

参数:

There is only one optional parameter in it:

1)chars - a string specifying

the set of characters to be removed.

If the optional chars parameter is not given, all leading

and trailing whitespaces are removed from the string.

返回值:

Returns a copy of the string with both leading and trailing characters removed.

# Python3 program to demonstrate the use of

# strip() method

string = " geeks for geeks "

# prints the string without stripping

print(string)

# prints the string by removing leading and trailing whitespaces

print(string.strip())

# prints the string by removing geeks

print(string.strip(' geeks'))

输出:

geeks for geeks

geeks for geeks

for

错误:

当我们尝试剥离字符串以外的任何内容时,都会出现运行时错误。系统给出的输出显示

# Python3 program to demonstrate the use of

# strip() method error

string = " geeks for geeks "

list =[1, 2, 3]

# prints the error message

print(list.strip())

输出:

Traceback (most recent call last):

File "/home/1bdead5a6ad1dbb0db1c6a2663874e4c.py", line 8, in

print(list.strip())

AttributeError:type object 'list' has no attribute 'strip'

实际应用:

给定一个字符串,请从开头和结尾删除单词“The”的出现。

# Python3 program to demonstrate the practical application

# strip()

string = " the King has the largest army in the entire world the"

# prints the string after removing the from beginning and end

print(string.strip(" the"))

输出:

King has the largest army in the entire world

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值