Home > Mobile >  Remove nonalpha, edit, add nonalpha
Remove nonalpha, edit, add nonalpha

Time:10-22

i want to edit a string after removing nonalpha chars, then move them in the proper place again. eg:

import re
string = input()
alphastring = re.sub('[^0-9a-zA-Z] ', '', string)
alphastring = alphastring[::2]

i want it to be as following:

  • string = "heompuem ykojua'rje awzeklvl."
  • alphastring = heompuemykojuarjeawzeklvl
  • alphastring = hopeyourewell
  • ?????? = hope you're well.

I tried fixing the problem with different sollutions but none give me the right output. I resorted to using RegEx which I'm not very familiar with. Any help would be greatly welcomed.

CodePudding user response:

I can't think of any reasonable way to do this with a regexp. Just use a loop that copies from input to output, skipping every other alphanumeric character.

copy_flag = True
string = input()
alphastring = ''
for c in string:
    if c.isalnum():
        if copy_flag:
            alphastring  = c
        copy_flag = not copy_flag
    else:
        alphastring  = c

CodePudding user response:

Here is an approach:

string = "heompuem ykojua'rje awzeklvl."
result, i = "", 0

for c, alph in ((c, c.isalnum()) for c in string)
    if not (alph and i%2):  # skip odd alpha-numericals
        result  = c
    i  = alph  # only increment counter for alpha-numericals
 
result
# "hope you're well."
  • Related