如何使用Python中的strip函数删除字符串中的空格和特定字符?
发布时间:2023-06-30 02:08:31
在Python中,可以使用strip函数来删除字符串中的空格和特定字符。strip函数是字符串对象的一个方法,它用于删除字符串开头和结尾的指定字符(默认为空格字符)。以下是使用strip函数的一些示例:
1. 删除字符串开头和结尾的空格:
string = " hello world " new_string = string.strip() print(new_string) # 输出: "hello world"
2. 删除字符串开头和结尾的特定字符:
string = "!!hello world!!"
new_string = string.strip("!")
print(new_string) # 输出: "hello world"
3. 删除字符串中的空格:
string = " hello world "
new_string = string.replace(" ", "")
print(new_string) # 输出: "helloworld"
4. 删除字符串中的特定字符:
string = "h-e-l-l-o w-o-r-l-d"
characters = ["-", " "]
for char in characters:
string = string.replace(char, "")
print(string) # 输出: "helloworld"
需要注意的是,strip函数只能删除字符串开头和结尾的字符,如果要删除字符串中间的特定字符,可以使用replace函数。另外,strip函数和replace函数都会生成一个新的字符串,原始字符串不会被修改,所以需要将新生成的字符串赋值给变量。
