简体   繁体   中英

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.ai/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?

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'

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

也许.replace(' ','') 。如果有很多空格, import re (正则表达式)将为您提供帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM