ThouWolfman
ThouWolfman

Reputation: 3

Trying to use a loop to take out certain character

for index in range(0,len(user_input)):
            if user_input[index] == ('-'):
                if (user_input[index - 1].isalpha() and user_input[index + 1].isalpha()):
                           target += user_input[index]
                else:
                    target =+ ' ' 
            elif user_input[index] == ("'"):
                if (user_input[index - 1].isalpha() and user_input[index + 1].isalpha()):
                           target += user_input[index]
                else:
                    target =+ ' ' 
    target = ''.join(target)
    
    target = target.split()

print(target)

Trying to have it take out certain characters I.E !#$% and keep - ' but when I print the statement its not displaying the input

Upvotes: 0

Views: 29

Answers (1)

Mike67
Mike67

Reputation: 11342

I'm not clear on your goal, but based on your existing logic, this may be what you want:

user_input = "j%k$l#m'n@python$'$!k#-#z-zll-X"
print(user_input)

target = ''

for index in range(0,len(user_input)):
    if user_input[index].isalpha():
        target += user_input[index]
    elif user_input[index] == ('-'):
        if (user_input[index - 1].isalpha() and user_input[index + 1].isalpha()):
            target += user_input[index]
        else:
            target += ' ' 
    elif user_input[index] == ("'"):
        if (user_input[index - 1].isalpha() and user_input[index + 1].isalpha()):
                   target += user_input[index]
        else:
            target += ' ' 
print('>',target)
target = ''.join(target)

print(target)

Output

jklm'npython k z-zll-X

--- Update ---

If the goal is just to remove certain characters from a string, there's a few ways to do that:

user_input = "T#wo #ro%%ads div!erged! in% a ye!ll!ow wood"

badlst = '!#$%'

### use loop ###
target = ''
for e in user_input:
   if not e in badlst:
       target += e

print(target)

### list comprehension ###
target = ''.join([e for e in user_input if e not in badlst])

print(target)

### replace ###
target = user_input
for e in badlst:
    target = target.replace(e,"")

print(target)

Output

Two roads diverged in a yellow wood
Two roads diverged in a yellow wood
Two roads diverged in a yellow wood

Upvotes: 1

Related Questions