How would I be able to make this if statement more efficient?
if ',' in my_string:
my_string = my_string.split(',', 1)[0]
return ', '
elif '.' in my_string:
my_string = my_string.split('.', 1)[0]
return '. '
elif '?' in my_string:
my_string = my_string.split('?', 1)[0]
return '? '
elif '!' in my_string:
my_string = my_string.split('!', 1)[0]
return '! '
elif ';' in my_string:
my_string = my_string.split(';', 1)[0]
return '; '
else:
self.qstring = my_string
return None
I could make a list like:
my_list = [',', '.', '?', '!', ';']
and loop through, but I'm not sure how to still use the else statement if I put it all in a loop. Any thoughts?
asked Sep 6, 2013 at 14:58
natsuki_2002
25.6k21 gold badges49 silver badges51 bronze badges
3 Answers 3
Loop over the list you have:
for delim in my_list:
if delim in my_string:
my_string = my_string.split(delim, 1)[0]
return delim + ' '
self.qstring = my_string
return None
Because the loop will return the part after the loop is not executed if any delimiter matched.
answered Sep 6, 2013 at 14:59
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.4k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Use re:
import re
(mystring, delim) = re.split(r'([,\.\?;] )', mystring, 1)[:2]
return delim
answered Sep 6, 2013 at 15:03
Ofir Israel
3,9432 gold badges17 silver badges13 bronze badges
Remove all the assignments to my_string. Since this is a local variable, this achieves nothing because the value is never returned.
answered Sep 6, 2013 at 15:00
kindall
185k36 gold badges291 silver badges321 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-py
my_stringis preserved somewhere? As your code stands, there is no point in assigning tomy_string, or even splitting the text, as you return immediately after the split and are thus discardingmy_string.