简体   繁体   中英

Trying to Iterate through strings to add certain characters to new string

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.

s 是原始字符串

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.

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]

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"]:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM