tags:

views:

37

answers:

2

I read the ini file to open a file in python. The thing is that the file info is sometimes inside the "..", but sometimes it's not.

For example,

fileA = "/a/b/c.txt"
fileB = /a/b/d.txt

Is there easy way to detect if a string is wrapped in "..", and return the string inside the quotation?

+2  A: 

To remove all leading and trailing quotes:

fileA = fileA.strip('"')
Magnus Hoff
+2  A: 

The simple detection would involve checking s[:1] == s[-1:] == '"' (carefully phrasing it with slicing rather than indexing to avoid exceptions if s is an empty string), and the conditional removal of exactly one quote from each end if one is present at both ends is

if s[:1] == s[-1:] == '"':
    s = s[1:-1]

Alternatively, the approach in @Magnus's answer, as he says, removes all leading and trailing quote, and does so unconditionally; so, for example, if s starts with three quotes but doesn't end with any (and in all sort of other weird cases, outside of your specs as stated), the snippet in my answer won't alter s, @Magnus's will strip the three leading quotes.

"You pay your money and you take your choice"... if you don't care one way or another (i.e. you're sure that the situation where the two answers differ is "totally and utterly impossible"...), then I think @Magnus's higher-abstraction-level approach is neater (but, it's a matter of style -- both his approach and mine are correct Python solutions when you don't care about unmatched or unbalanced quotes;-).

Alex Martelli
@Alex : s[0] == s[-1] == '"' wouldn't be the same, or better?
prosseek
@prosseek, it would give an exception if `len(s) == 0`; if you're magically certain that can't happen, or _want_ an exception when `s` is an empty string, indexing instead of slicing can be minutely faster.
Alex Martelli