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

How to remove all spaces in a string in Python

青灯夜游
Release: 2019-01-19 14:53:56
Original
26229 people have browsed it

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)) ;
Copy after login

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)) ;
Copy after login

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)) ;
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template