Home  >  Article  >  Backend Development  >  How to remove all spaces in a string in Python

How to remove all spaces in a string in Python

青灯夜游
青灯夜游Original
2019-01-19 14:53:5626179browse

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]

How to remove all spaces in a string in Python

##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)) ;

Output:

How to remove all spaces in a string in Python

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)) ;

Output:

How to remove all spaces in a string in Python

Using Python regular expressions

Python has added the re module since version 1.5, which provides Perl-style regular expression patterns. The

re module brings full regular expression capabilities to the Python language.

#导入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)) ;

Output:

How to remove all spaces in a string in Python

The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn