简体   繁体   English

在字母前后删除字符串中的空格

[英]Remove spaces from string after and before letter

I have a quite a few sums of strings that look like this: "a name / another name / something else". 我有很多类似的字符串:“一个名称/另一个名称/其他名称”。

I want to get to this: "a name/another name/something else". 我要说的是:“一个名字/另一个名字/其他”。

Basically removing the spaces before and after the forward slashes only (not between the words themselves). 基本上只删除正斜杠前后的空格(而不是单词本身之间的空格)。

I know nothing about programming but I looked and found that this can be done with Python and Regex. 我对编程一无所知,但我发现并发现可以使用Python和Regex完成。 I was a bit overwhelmed though with the amount of information I found. 尽管我发现的信息量让我有些不知所措。

You can use the pattern: 您可以使用以下模式:

(?:(?<=\/) | (?=\/))
  • (?: Non capturing group. (?:非捕获组。
  • (?<=\\/) Lookbehind for / . (?<=\\/)/
  • | OR 要么
  • (?=\\/) Positive lookahead for / . (?=\\/)正向/向前看。
  • ) Close non capturing group. )关闭非捕获组。

You can try it live here . 您可以在这里试用。


Python snippet: Python片段:

import re
str = 'a name / another name / something else'
print(re.sub(r'(?:(?<=\/) | (?=\/))','',str))

Prints: 打印:

a name/another name/something else

Here is an answer without using regex that I feel is easier to understand 这是一个不用正则表达式的答案,我觉得这更容易理解

string = "a name / another name / something else"
edited = "/".join([a.strip() for a in string.split("/")])
print(edited)

output: 输出:

a name/another name/something else

.join() joins elements of a sequence by a given seperator, docs .join()通过给定的分隔符docs连接序列的元素

.strip() removes beginning and trailing whitespace, docs .strip()删除开头和结尾的空格, docs

.split() splits the string into tokens by character, docs .split()按字符, 文档将字符串拆分为标记

There's no need for regex here, since you're simply replacing a string of literals. 这里不需要正则表达式,因为您只需要替换字符串即可。

str = "a name / another name / something else"
print(str.replace(" / ", "/"))

This pattern will match for any amount of whitespace surrounding / and remove it. 此模式将匹配/周围的任意数量的空格并将其删除。 I think the regex is relatively easy to understand 我认为正则表达式相对容易理解

\s*([\/])\s*

Has a capturing group that matches the backslash (that's what the middle part is). 有一个与反斜杠匹配的捕获组(这就是中间部分)。 The s* parts match whitespace (at least one up to any amount of times). s*部分与空格匹配(至少一个,最多不限次数)。

You can then replace these matched strings with just a / to get rid of all the whitespace. 然后,您可以仅用/替换这些匹配的字符串,以消除所有空白。

str1是您的字符串:

re.sub(" / ", "/" ,str1)

Use the following code to remove all spaces before and after the / character: 使用以下代码删除/字符之前和之后的所有空格:

import re
str = 'a name /  another name / something else'
str = re.sub(r'(?:(?<=\/)\s*|\s*(?=\/))','', str)

Check this document for more information. 查看此文档以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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