如何使用Python的strip函数删除字符串两侧的空格?
发布时间:2023-07-02 18:19:52
Python的strip()函数是用来删除字符串两侧的空格(或其他指定字符)的。可以使用以下方式来使用strip()函数删除字符串两侧的空格。
1. 基本用法:
string = " Hello, World! " new_string = string.strip() print(new_string) # Output: "Hello, World!"
在上面的例子中,strip()函数没有传递参数,默认删除字符串两侧的空格。
2. 删除指定字符:
strip()函数还可以接受一个参数,该参数指定要删除的字符。例如:
string = "***Hello, World!***"
new_string = string.strip("*")
print(new_string) # Output: "Hello, World!"
上面的例子中,strip("*")函数删除了字符串两侧的星号字符。
3. 删除换行符:
strip()函数还可以删除字符串两侧的换行符。例如:
string = "
Hello, World!
"
new_string = string.strip("
")
print(new_string) # Output: "Hello, World!"
上面的例子中,strip("
")函数删除了字符串两侧的换行符。
4. 链式调用:
strip()函数可以和其他字符串方法一起使用,以实现更复杂的字符串操作。例如,先使用strip()函数删除字符串两侧的空格,然后再使用upper()方法将字符串转换为大写:
string = " hello, world! " new_string = string.strip().upper() print(new_string) # Output: "HELLO, WORLD!"
在上面的例子中,strip()函数先删除了字符串两侧的空格,然后upper()方法将字符串转换为大写。
总结:
Python的strip()函数是用来删除字符串两侧的空格(或其他指定字符)的。可以通过传递参数来指定要删除的字符。strip()函数可以在字符串的任何位置使用,并且可以和其他字符串方法一起使用。
