简体   繁体   中英

How to generalize a for loop for all alfanumerical characters

I want to preface this by saying that I'm fully aware that you can simplify this whole endeavor by avoiding the loop in the first place, but this is a longer project, so let's please just assume the original loop has to stay.

I created a loop that turns a string into a list at the empty space between words.

string= "This my string"
my_list = []
word = ""

for char in string:
    if char != " ":
        word += char
        if char is string[-1]:
            my_list.append(word)
    else:
        my_list.append(word)
        word = ""

The output therefore is:

['This', 'is', 'my', 'string.']

Now I would like to add a placeholder to the if char != " " , so I can later input any alphanumeric character to split the string at. So if I input i into this placeholder variable, the split would look like this:

['Th', 's my str', 'ng.']

I've attempted doing so with %s , but can't get it to work.

So how can I change/add to this loop to have a placeholder included?

Is that what you are looking for?

string= "This my string"
my_list = []
word = ""
character = " " # change for the char you want to split on

for char in string:
    if char != character:
        word += char
        if char is string[-1]:
            my_list.append(word)
    else:
        my_list.append(word)
        word = ""

It may be simpler to just use string.split(" ") or string.split(character) in your case.

You don't need to check if char is string[-1] every iteration just append word at the end after the loop. Also string overwrites the builtin string name.

As for changing the delimiter just change it at the beginning of the program

my_string = "This my string"
my_list = []
word = ""
delimiter = "i"

for char in my_string:
    if char != delimiter:
        word += char
    else:
        my_list.append(word)
my_list.append(word)
            

Result:

['Th', 's my str', 'ng']

You can use split() function to split strings. For case I, you can use string.split(" ") For case II, you can use string.split("i")

Or you can add any character inside split(), like: string.split(char)

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