Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading