How do I coalesce a sequence of identical characte

2020-03-02 03:09发布

Suppose I have this:

My---sun--is------very-big---.

I want to replace all multiple hyphens with just one hyphen.

10条回答
迷人小祖宗
2楼-- · 2020-03-02 03:41
import re

astr='My---sun--is------very-big---.'

print(re.sub('-+','-',astr))
# My-sun-is-very-big-.
查看更多
萌系小妹纸
3楼-- · 2020-03-02 03:48

I have

my_str = 'a, b,,,,, c, , , d'

I want

'a,b,c,d'

compress all the blanks (the "replace" bit), then split on the comma, then if not None join with a comma in between:

my_str_2 = ','.join([i for i in my_str.replace(" ", "").split(',') if i])
查看更多
姐就是有狂的资本
4楼-- · 2020-03-02 03:49

if you don't want to use regular expressions:

    my_string = my_string.split('-')
    my_string = filter(None, my_string)
    my_string = '-'.join(my_string)
查看更多
Lonely孤独者°
5楼-- · 2020-03-02 03:52

How about an alternate without the re module:

'-'.join(filter(lambda w: len(w) > 0, 'My---sun--is------very-big---.'.split("-")))

Or going with Tim and FogleBird's previous suggestion, here's a more general method:

def coalesce_factory(x):
    return lambda sent: x.join(filter(lambda w: len(w) > 0, sent.split(x)))

hyphen_coalesce = coalesce_factory("-")
hyphen_coalesce('My---sun--is------very-big---.')

Though personally, I would use the re module first :)

  • mcpeterson
查看更多
登录 后发表回答