Python中如何使用strip()函数删除字符串中的空格
在Python中,可以使用strip()函数删除字符串中的空格。strip()函数是一个字符串方法,用于去除字符串开头和结尾的空格和换行符。下面是使用strip()函数删除字符串中的空格的方法。
方法一:删除开头和结尾的空格
string = " hello world " new_string = string.strip() print(new_string) # 输出: "hello world"
在上面的例子中,strip()函数会删除字符串变量string开头和结尾的空格,并将修改后的字符串赋值给new_string变量。然后,使用print()函数打印new_string变量的值,即删除了空格的字符串"hello world"。
方法二:删除开头的空格
string = " hello world " new_string = string.lstrip() print(new_string) # 输出: "hello world "
在上面的例子中,lstrip()函数会删除字符串变量string开头的空格,并将修改后的字符串赋值给new_string变量。然后,使用print()函数打印new_string变量的值,即删除了开头的空格的字符串"hello world "。
方法三:删除结尾的空格
string = " hello world " new_string = string.rstrip() print(new_string) # 输出: " hello world"
在上面的例子中,rstrip()函数会删除字符串变量string结尾的空格,并将修改后的字符串赋值给new_string变量。然后,使用print()函数打印new_string变量的值,即删除了结尾的空格的字符串" hello world"。
需要注意的是,strip()、lstrip()和rstrip()函数只会删除开头和结尾的空格,而不会删除字符串中间的空格。如果需要删除字符串中间的空格,可以结合使用split()函数和join()函数。
方法四:删除字符串中的所有空格
string = " hello world " new_string = ''.join(string.split()) print(new_string) # 输出:"helloworld"
在上面的例子中,split()函数会根据空格将原始字符串分割成一个字符串列表,然后使用join()函数将列表中的字符串元素合并成一个新的字符串,同时删除了字符串中的所有空格。最后,将新的字符串赋值给new_string变量,并使用print()函数打印new_string变量的值。
