Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you split a string at a specific point?

I am new to python and want to split what I have read in from a text file into two specific parts. Below is an example of what could be read in:

f = ['Cats','like','dogs','as','much','cats.'][1,2,3,4,5,4,3,2,6]

So what I want to achieve is to be able to execute the second part of the program is:

words = ['Cats','like','dogs','as','much','cats.']

numbers = [1,2,3,4,5,4,3,2,6]

I have tried using:

words,numbers = f.split("][")

However, this removes the double bracets from the two new variable which means the second part of my program which recreates the original text does not work.

Thanks.

like image 273
alice Avatar asked Dec 23 '22 21:12

alice


1 Answers

I assume f is a string like

f = "['Cats','like','dogs','as','much','cats.'][1,2,3,4,5,4,3,2,6]" 

then we can find the index of ][ and add one to find the point between the brackets

i = f.index('][')
a, b = f[:i+1], f[i+1:]
print(a)
print(b)

output:

['Cats','like','dogs','as','much','cats.']
[1,2,3,4,5,4,3,2,6]
like image 149
Patrick Haugh Avatar answered Jan 10 '23 10:01

Patrick Haugh