(Aug-06-2023, 07:17 AM)Pedroski55 Wrote: [ -> ]How about this, thought of it just now:
Then you are back to original problem he try to avoid with many call to
replace()
if split on several character.
Now have to call new
split()
many time's if add new character to split on.
If you try with mystring under you will see the problem.
>>> mystring = 'ab|cd!ef?gh!ij*kl!mn|'
>>> ''.join(c if not c in '|!?*' else ' ' for c in s).split()
['ab', 'cd', 'ef', 'gh', 'ij', 'kl', 'mn']
Also a tips in or other code try to avoid
Never use for i in range(len(sequence)):
If i write my one liner over to a standard loop,see that there in no need for
range(len(sequence)
.
Just loop over mystring and no need to manipulate the index.
def split_extend(mystring: str, chr_split: str ) -> list:
result = ''
for c in mystring:
if c not in chr_split:
result += c
else:
result += ' '
return result.split()
if __name__ == '__main__':
mystring = 'ab|cd!ef?gh!ij*kl!mn|'
chr_split = '|!?*'
print(split_extend(mystring, chr_split))
Output:
['ab', 'cd', 'ef', 'gh', 'ij', 'kl', 'mn']
The cooler way,but it can be harder to read,so line is in borderland of what should do in one line.
def split_extend(mystring: str, chr_split: str ) -> list:
return ''.join(c if not c in chr_split else ' ' for c in mystring).split()
if __name__ == '__main__':
mystring = 'ab|cd!ef?gh!ij*kl!mn|'
chr_split = '|!?*'
print(split_extend(mystring, chr_split))
Output:
['ab', 'cd', 'ef', 'gh', 'ij', 'kl', 'mn']