strip()函数用于去除字符串中的指定字符,默认情况下会去除字符串首尾的空格或换行符。
函数语法如下:
string.strip([chars])
参数说明:
- chars:可选参数,指定要去除的字符。如果不提供该参数,默认会去除字符串首尾的空格或换行符。
例子:
string = " Hello World " print(string.strip()) # 输出:Hello World string = "##Hello World##" print(string.strip('#')) # 输出:Hello World
在第一个例子中,strip()函数会去除字符串首尾的空格。
在第二个例子中,strip(‘#’)函数会去除字符串首尾的"#"字符。