简体   繁体   中英

Remove multiples of character sequence from string

If I had a string like so:

my_string = 'this is is is is a string'

How would I remove the multiple is s so that only one will show?

This string could contain any number of is in there such as

my_string = 'this is is a string'
other_string = 'this is is is is is is is is a string'

A regex solution would be possible I suppose however I'm not sure how to go about it. Thanks.

You can use itertools.groupby

from itertools import groupby
a = 'this is is is is a a a string string a a a'
print ' '.join(word for word, _ in groupby(a.split(' ')))

Here is my approach:

my_string = 'this is is a string'
other_string = 'this is is is is is is is is a string'
def getStr(s):
    res = []
    [res.append(i) for i in s.split() if i not in res]
    return ' '.join(res)

print getStr(my_string)
print getStr(other_string)

Output:

this is a string
this is a string

UPDATE The regex way to attack it:

import re
print ' '.join(re.findall(r'(?:^|)(\w+)(?:\s+\1)*', other_string))

LIVE DEMO

If you would like to remove all duplicates after one another, you can try

l = my_string.split()
tmp = [l[0]]
for word in l:
    if word != tmp[-1]:
        tmp.append(word)
s = ''
for word in tmp:
    s += word + ' '
my_string = s

of course, if you want it smarter than this, it is going to be more complicated.

For oneliners:

>>> import itertools
>>> my_string = 'this is is a string'
>>> " ".join([k for k, g in itertools.groupby(my_string.split())])
'this is a string'

Regex to the rescue!

((\b\w+\b)\s*\2\s*)+
# capturing group
# inner capturing group
# ... consisting of a word boundary, at least ONE word character and another boundary
# followed by whitespaces
# and the formerly captured group (aka the inner group)
# the whole pattern needs to be present at least once, but can be there
# multiple times

Python Code

import re

string = """
this is is is is is is is is a string
and here is another another another another example
"""
rx = r'((\b\w+\b)\s*\2\s*)+'

string = re.sub(rx, r'\2 ', string)
print string
# this is a string
# and here is another example

Demos

See a demo for this approach on regex101.com as well as on ideone.com

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