Home > Blockchain >  Trying to Iterate through strings to add certain characters to new string
Trying to Iterate through strings to add certain characters to new string

Time:10-18

I am trying to remove certain characters from a string and it was suggested that i try and make a new string and just add characters that meet my criteria. I use a for loop to iterate through the string but then characters arent added to the new string-it prints a blank string. Ill include an ss.

the s is the original string

CodePudding user response:

You should use:

answer_string  = s[i]

As, your current statement answer_string s is not doing what you are hoping for.

This is what I understood from the given context. It would be better if you could post a code snippet with reference for better understanding the issue.

CodePudding user response:

you should use the in operator for comparing a value with multiple other values:

if s[i] not in 'AEIOUaeiou' or s[i-1] == ' ':
    # if you prefer lists / tuples / sets of characters, you can use those instead:
    # if s[i] not in ['A', 'E', 'I', 'O', ...]
    answer_string  = s[i]

CodePudding user response:

You have to check the character with each on it's own. That would be:

if s[i] != "A" or s[i] != "B" ... :

A more elegant solution would be:

if s[i] not in ["ABCD..."]:

Also what @avats said, you should be adding the single character, not the whole string

answer_string  = s[i]

To make the checking case insensitive, so you wouldn't have to type out all the uppercase letters and lowercase, use lower():

if s[i].lower() not in ["abcd"]:
  • Related