0

So I have an Excel column which contains Python lists.

enter image description here

The problem is that when I'm trying to loop through it in Python it reads the cells as str. Attempt to split it makes the items in a list generate as e.g.:

list = ["['Gdynia',", "'(2262011)']"]

list[0] = "['Gdynia,'"

list1 = "'(2261011)']"

I want only to get the city name which is e.g. 'Gdynia' or 'Tczew'. Any idea how can I make it possible?

1
  • 2
    Did you try to use pandas? Commented Jun 7, 2021 at 11:34

2 Answers 2

1

You can split the string at a desired symbol, ' would be good for your example. Then you get a list of strings and you can chose the part you need.

str = "['Gdynia',", "'(2262011)']"
str_parts = str.split("'") #['[', 'Gdynia', ',', '(2262011)', ']']
city = str_parts[1] #'Gdynia'
Sign up to request clarification or add additional context in comments.

Comments

1

Solution with re:

import re

data = ["['Gdynia', '(2262011)'",
        "['Tczew', '(2214011)']",
        "['Zory', ’(2479011)']"]

r = re.compile("'(.*?)'")
print(*[r.search(s).group(1) for s in data], sep='\n')

Output

Gdynia
Tczew
Zory

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.