使用Python中的string.strip(char)函数从字符串中删除开头和结尾的字符/字符串

先决条件: Python-函数string.strip()

在上一篇文章中,我们讨论了如何删除前导和尾随空格,在这里我们讨论了如何使用它从字符串中删除前导和尾随字符/字符串?string.strip()

语法: string.strip([ char ])

[ char ]是一个可选参数,它指定要从字符串开头和结尾删除的特定字符或字符集。

示例

    Input string: "#@# Hello world! #@#"

    chars to remove: "#@#"

    Output string: " Hello world! "

Python代码可从字符串中删除开头和结尾字符或字符集

# Python code to remove leading & trailing chars

# An example of string.strip(char) function)

# defining string 

str_var = "#@# Hello world! #@#"

#printing actual string

print "Actual string is:\n", str_var

# printing string without

# leading & trailing chars

print "String w/o spaces is:\n", str_var.strip('#@#')

输出结果

Actual string is:

#@# Hello world! #@#

String w/o spaces is:

 Hello world!

它不会删除单词之间的字符

在此示例中,在字符串之前和之后以及单词之间存在“#@#”,但是函数将仅删除字符串之前(“ Leading”)和“ Trailing”之后的“#@#”,而不会删除“字词之间的#@#”。考虑给定的例子,

# Python code to remove leading & trailing chars

# An example of string.strip(char) function)

# defining string 

str_var = "#@# Hello #@# world! #@#"

#printing actual string

print "Actual string is:\n", str_var

# printing string without

# leading & trailing chars

print "String w/o spaces is:\n", str_var.strip('#@#')

输出结果

Actual string is:

#@# Hello #@# world! #@#

String w/o spaces is:

 Hello #@# world!

以上是 使用Python中的string.strip(char)函数从字符串中删除开头和结尾的字符/字符串 的全部内容, 来源链接: utcz.com/z/340688.html

回到顶部