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?
>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.