I want to split this string:
"Oscar Wilde, Sophocles, and Lin-Manuel Miranda"
to get this list ('and'
is discarded):
["Oscar Wilde", "Sophocles", "Lin-Manuel Miranda"]
I want to split this string:
"Oscar Wilde, Sophocles, and Lin-Manuel Miranda"
to get this list ('and'
is discarded):
["Oscar Wilde", "Sophocles", "Lin-Manuel Miranda"]
my_name_str = "Oscar Wilde, Sophocles, and Lin-Manuel Miranda"
cleaned_name_str = my_name_str.replace(", and ", ", ")
print(my_name_list)
# "Oscar Wilde, Sophocles, Lin-Manuel Miranda"
my_name_list = my_name_str.split(",")
print(my_name_list)
# ["Oscar Wilde", " Sophocles", " Lin-Manuel Miranda"]
clean_name_list = [i.strip() for i in my_name_list]
print(clean_name_list)
# ["Oscar Wilde", "Sophocles", "Lin-Manuel Miranda"]
There are several ways you can remove the and, this is just one.
The key things here are split
which splits the string on a substring and strip
which removes trailing and leading whitespace
The [item for item in list]
bit is called "list comprehension
" and is super powerful in python (there's also "dictionary comprehension
") which is basically how filtering is done in python and can often clean up for loops.
You could split using a regex:
s = "Oscar Wilde, Sophocles, and Lin-Manuel Miranda"
import re
out = re.split(',\s*(?:and\s*)?', s)
',\s*(?:and\s*)?'
means a comma optionally followed by spaces and and
.
Output:
['Oscar Wilde', 'Sophocles', 'Lin-Manuel Miranda']
you can replace the "and" to a comma and split
anywhere it finds a comma, and then iterate over the list to clear any whitespace around with the strip.()
txt = "Oscar Wilde, Sophocles and Lin-Manuel and Miranda"
elem = txt.replace(' and ',',').split(',')
elem = [x.strip() for x in elem]
# print(elem): ['Oscar Wilde', 'Sophocles', 'Lin-Manuel', 'Miranda']
my_name_str = "Oscar Wilde, Sophocles, and Lin-Manuel Miranda"
my_name_split = my_name_str.split(' and ')
my_name_str = ''
for i in my_name_split:
my_name_str += i
my_name_split = my_name_str.split(',')
print(my_name_split)