Python字符串| strip()

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

null
string.strip([chars])Parameter: 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.Return Value:Returns a copy of the string with both leading and trailing characters removed.

Python3

# 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 geeksfor

Python3

# Python Program to demonstrate use of strip() method
str1 = 'geeks for geeks'
# Print the string without stripping.
print (str1)
# String whose set of characters are to be
# remove from original string at both its ends.
str2 = 'ekgs'
# Print string after stripping str2 from str1 at both its end.
print (str1.strip(str2))


输出:

geeks for geeks for

上述代码的使用: 我们首先构造一个字符串str1=’geeks for geeks’ 现在我们在str1上调用strip方法,并将str2=’ekgs’作为参数传递。 现在python解释器从左边跟踪str1。如果str1存在于str2中,则删除该字符。 否则它将停止跟踪。 现在python解释器从右边跟踪str1。如果str1存在于str2中,则删除该字符。 否则它将停止跟踪。 现在它终于返回结果字符串。 当我们在没有参数的情况下调用strip()时,它会删除前导空格和尾随空格。

Python3

# Python Program to demonstrate use of strip() method without any argument
str1 = """    geeks for geeks    """
# Print the string without stripping.
print (str1)
# Print string after removing all leading
# and trailing whitespaces.
print (str1.strip())


输入:

    geeks for geeks     

输出:

geeks for geeks

实际应用: 给定一个字符串,从开头和结尾删除单词“the”的出现。

python

# 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" ))


输入:

the King has the largest army in the entire world the

输出:

King has the largest army in the entire world

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享