Alex
Alex

Reputation: 1537

How to remove space after slash "/"

I am working with Python and I want to remove blank spaces in the URLs, in order to restore broken links.

This is a typical case I have to deal with.

Text about something https:// sr.a i/gMF

The link has one blank space after the slash (/) which can be expected. But also it can have other blank spaces randomly distributed.

First, I want to fix if present the space after the slash (/)

.replace('/ ', '//')

This code works fine to replace the blank space immediately after the slash, but is there a way to fix the link if the blank space occurs anywhere else WITHOUT removing all the white spaces since I need to preserve the meaning of the text?

Upvotes: 1

Views: 2688

Answers (3)

Nathan Smith
Nathan Smith

Reputation: 681

Use the string.replace() function, and simply replace with white space with empty string.

>>> my_string = "https:// sr.a i/gMF"
>>> my_string
'https:// sr.a i/gMF'
>>> my_string.replace(" ","")
'https://sr.ai/gMF'

Upvotes: 2

FreshD
FreshD

Reputation: 3112

Use the regexp lib https://docs.python.org/3.6/library/re.html with the following regexp

import re
text = re.sub(r"[/]\s", "/", text)
# r"" --> regexp in python
# [/] --> slash
# \s  --> blank

In this online regexp editor you can play around an make the regexp more stable for certain corner cases

Upvotes: 2

chuchienshu
chuchienshu

Reputation: 45

Maybe .replace(' ','') work.If there are many blank space, import re (regular expression)will help you.

Upvotes: 1

Related Questions