To remove all spaces in a string in Python: use the replace() function, use the split() function join() function, and use Python regular expressions. The following article will introduce these methods in detail, hoping to be helpful to everyone. [Related video tutorial recommendations: Python tutorial]
##Use the replace() function
We can use the replace() function to replace all spaces (" ") with ("")def remove(string): return string.replace(" ", ""); string = ' H E L L O ! '; print("原字符串:"+string) ; print("\n新字符串:"+remove(string)) ;
Use the split() function join() function
The split() function slices the string by specifying the delimiter and returns all the units of the split string. Character list. Then, we iteratively join these characters using the join() function.def remove(string): return "".join(string.split()); string = 'w o r l d '; print("原字符串:"+string) ; print("\n新字符串:"+remove(string)) ;
Using Python regular expressions
#导入re 模块 import re def remove(string): pattern = re.compile(r'\s+'); return re.sub(pattern,'', string); string = 'P y t h o n'; print("原字符串:"+string); print("\n新字符串:"+remove(string)) ;
The above is the detailed content of How to remove all spaces in a string in Python. For more information, please follow other related articles on the PHP Chinese website!