is there a way in python to only take from a file a string in between certain characters? for example, if i have this in a file:

city state[long, lat]population

how can i take from the line just what is in between the brackets (that is, come up with [long, lat])? please help me. thank you!

Recommended Answers

All 6 Replies

i have to read from a file. i need to find the information between certain characters for every line in the file, not just from one string set. but thank you anyway

And isn't that line a string?

well yes, i suppose so, but i need to add what's in between the []s to a list, and when i tried that definition, i got a typeerror: can only concatenate list (not "tuple") to list

Are you sure that you are appending the second returned value between the separators?

@pansquare, pyTony has provided the correct answer. However you seem to be not bothering to search the documentation on

s.partition(sep) returns a tuple which essentially is a set of 3 values (before, separator, after)

'foo[baz]bar'.partition('[') returns a tuple 'foo', '[', 'baz]bar' -> (before, _, after)
after.partition(']') returns a tuple 'baz', ']', 'bar' -> (mid, _, after)

What needs to be returned is before, mid, after which is a tuple while you only need mid for l.append(mid).
The file in question is essentially a collection of strings.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.