How to generalize a for loop for all alfanumerical characters

Question:

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?

Asked By: CarrieH

||

Answers:

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.

Answered By: PhilippB

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']
Answered By: Jab

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)

Answered By: Md Abuzar Manazir
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.