How to move all special characters to the end of the string in Python?

advertisements

I'm trying to filter all non-alphanumeric characters to the end of the strings. I am having a hard time with the regex since I don't know where the special characters we be. Here are a couple of simple examples.

hello*there*this*is*a*str*ing*with*asterisks
and&this&is&a&str&ing&&with&ampersands&in&i&t
one%mo%refor%good%mea%sure%I%think%you%get%it

How would I go about sliding all the special characters to the end of the string?

Here is what I tried, but I didn't get anything.

re.compile(r'(.+?)(\**)')
r.sub(r'\1\2', string)

Edit:

Expected output for the first string would be:

hellotherethisisastringwithasterisks********


There's no need for regex here. Just use str.isalpha and build up two lists, then join them:

strings = ['hello*there*this*is*a*str*ing*with*asterisks',
'and&this&is&a&str&ing&&with&ampersands&in&i&t',
'one%mo%refor%good%mea%sure%I%think%you%get%it']
for s in strings:
    a = []
    b = []
    for c in s:
        if c.isalpha():
            a.append(c)
        else:
            b.append(c)
    print(''.join(a+b))

Result:

hellotherethisisastringwithasterisks********
andthisisastringwithampersandsinit&&&&&&&&&&&
onemoreforgoodmeasureIthinkyougetit%%%%%%%%%%

Alternative print() call for Python 3.5 and higher:

print(*a, *b, sep='')