Python strip 字符串函数会移除文本的右侧和左侧的指定字符(默认是空格),并且此方法会返回字符串的一个新副本。
此函数是 right 和 left strip 字符串方法的组合,它会移除前导和尾随的空格。下面展示了 Python strip 字符串函数的语法。
String_Value.strip(Chars)
- String_Value:一个有效参数。
- Chars:此参数是可选的。如果省略,则默认参数为白色空格。因此,此方法会移除前导和尾随的空格。要更改默认值,请指定要从字符串中移除的前导和尾随字符。
Python strip 字符串函数示例
以下示例集有助于了解此 strip 方法。在此方法示例中,我们首先声明了字符串变量 Str1,并为其分配了一个在两侧都有空格的字符串。
第一个语句使用 strip 字符串函数移除了变量 Str1 的左侧和右侧的空格,并打印了输出。
从接下来的两个语句输出中,您可以看到此方法返回了新输出,而不是修改原始字符串。在下一行中,我们将结果赋值给自己,以便在Python中更改原始字符串。
如前所述,Python strip 字符串函数允许使用参数。在接下来的两个语句中,我们在两侧都有零,并且我们传递了‘0’作为参数,这意味着它移除了两侧的零。接下来,我们使用了两个要移除的字符(+ 和 *)。
str5 代码块使用此方法仅移除了给定句子的前导字符或左侧字符。最后两个语句仅移除了字符串的右侧或尾随字符。请参阅right和left函数文章。
Str1 = ' Tutorial Gateway ';
Str2 = Str1.strip()
print('Remove White sapces using this is =', Str2)
# Observe the Original
print('Converted is =', Str1.strip())
print('Original is =', Str1)
# Performing function directly
Str3 = '00000000Tutorial Gateway00000000'.strip('0')
print("Delete 0's using this is =", Str3)
Str4 = '+++++Tutorial Gateway****'.strip('+*')
print('Remove + and * on both using this is =', Str4)
# Left
Str5 = '***********Tutorial Gateway'.strip('*')
print('Delete Left Side using this is =', Str5)
# Right
Str6 = 'Tutorial Gateway========='.strip('=')
print('Remove Right Side using this is =', Str6)
