如何使用Python中的strip函数删除字符串开头和结尾的空格?
发布时间:2023-07-01 08:24:30
在Python中,可以使用字符串的strip()方法来删除字符串开头和结尾的空格。strip()方法返回一个去除开头和结尾空格的字符串副本,原字符串不会被修改。该方法也可以用于去除其它字符,不仅仅只是空格。下面是一些使用strip()函数删除字符串开头和结尾空格的示例。
1. 基本使用:
string = " Hello, World! " stripped_string = string.strip() print(stripped_string) # 输出:"Hello, World!"
在这个例子中,原始字符串" Hello, World! "在被strip()处理后,去除了开头和结尾的空格,得到"Hello, World!"。
2. 删除指定字符:
string = "*~*~*Hello, World!*~*~*"
stripped_string = string.strip("*~")
print(stripped_string) # 输出:"Hello, World!"
在这个例子中,strip()方法的参数"*~"指定了需要删除的字符,结果字符串stripped_string为"Hello, World!"。注意,在这种情况下,strip()方法只删除了开头和结尾的指定字符,而中间的字符没有被改变。
3. 只删除开头或结尾的空格:
string = " Hello, World! " left_stripped_string = string.lstrip() right_stripped_string = string.rstrip() print(left_stripped_string) # 输出:"Hello, World! " print(right_stripped_string) # 输出:" Hello, World!"
lstrip()方法只删除字符串开头的空格,rstrip()方法只删除字符串结尾的空格。
4. 处理多行字符串:
string = """
Hello, World!
"""
stripped_string = string.strip()
print(stripped_string) # 输出:"Hello, World!"
当字符串包含多行时,strip()方法会删除所有行的开头和结尾的空格。
需要注意的是,strip()方法仅删除开头和结尾的空格,中间的空格将保留不变。如果需要完全删除所有空格,可以使用字符串的replace()方法:
string = " Hello, World! "
no_space_string = string.replace(" ", "")
print(no_space_string) # 输出:"Hello,World!"
以上就是使用Python中的strip()函数删除字符串开头和结尾的空格的方法和示例。希望对你有所帮助!
