Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Splitting Array of Strings [duplicate]

Tags:

python

I have a list in Python that looks like this:

["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"]

I would like to split each string into a comma-separated list and store the result, and also convert each word to lowercase:

[['hello','my','name','is','john'], ['good','afternoon','my','name','is','david'],['i','am','three','years','old']]

Any suggestions how this could be done? Thank you.

like image 920
Thomas Moore Avatar asked Oct 15 '25 07:10

Thomas Moore


2 Answers

You can simply replace the comma with space and strip the rest of the string.

strList = ["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"]
[i.lower().replace(',', '').split() for i in strList]
like image 77
sanyam Avatar answered Oct 21 '25 03:10

sanyam


An approach using rstrip on each word :)

ls = ["Hello, My Name is John", "Good Afternoon, my name is David", "I am three years old"]

output_ls = [[word.lower().rstrip(',') for word in sentence.split()] for sentence in ls]

output:

[['hello', 'my', 'name', 'is', 'john'], ['good', 'afternoon', 'my', 'name', 'is', 'david'], ['i', 'am', 'three', 'years', 'old']]
like image 41
LeKhan9 Avatar answered Oct 21 '25 01:10

LeKhan9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!