Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python getting part of string based on condtion

Hi I am pretty new to Python and is currently looking for a way to effectively get a part of a string from a column based on a condition.

I currently have a column with the address.
It looks something like this.

data = {'addr': ['Seoul Gangnam Apgujeong 38-5', 'Seoul Songpa Jamsil 40-1 5-1302', 'Jeju Jeju Aewol 31-5', 'Busan Haeuondae Centum 70-1 7-141']}

I want to extract the second and the third value of the string.
So the result should look something like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data = {'addr': ['Gangnam Apgujeong', 'Songpa Jamsil', 'Jeju Aewol', 'Haeuondae Centum']}

Any sort of feedback would be appreciated!!
Thank you in advance!!

>Solution :

You can use list comprehension with split, slicing, and join:

data = {'addr': ['Seoul Gangnam Apgujeong 38-5', 'Seoul Songpa Jamsil 40-1 5-1302', 'Jeju Jeju Aewol 31-5', 'Busan Haeuondae Centum 70-1 7-141']}
output = {'addr': [' '.join(s.split()[1:3]) for s in data['addr']]}
print(output) # {'addr': ['Gangnam Apgujeong', 'Songpa Jamsil', 'Jeju Aewol', 'Haeuondae Centum']}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading