公告
财富商城
积分规则
提问
发文
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.
import re astr='My---sun--is------very-big---.' print(re.sub('-+','-',astr)) # My-sun-is-very-big-.
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])
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)
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 :)
最多设置5个标签!
I have
I want
compress all the blanks (the "replace" bit), then split on the comma, then if not None join with a comma in between:
if you don't want to use regular expressions:
How about an alternate without the re module:
Or going with Tim and FogleBird's previous suggestion, here's a more general method:
Though personally, I would use the re module first :)