Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

permissive equality test on string

Tags:

python

path

I'm a python newbie with a problem too hard to tackle.

I have a string defining a path, were all the spaces have been converted to underscores. How can I find if it corresponds to a real path?

e.g. a string like /some/path_to/directory_1/and_to/directory_2
with a real path: /some/path_to/directory 1/and_to/directory 2

notice that the real path can contain BOTH spaces and underscores.

How can I feed it to os.path.exists() ???

thanks alessandro

like image 787
alessandro Avatar asked Sep 27 '10 09:09

alessandro


People also ask

How do you test for equality of strings?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

Can strings be equality == operator?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do you check if a variable is equal to a string?

To check if a variable contains a value that is a string, use the isinstance built-in function. The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.

Can you use comparison operators with strings?

The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.


1 Answers

Use glob but replacing every underscore with a range [ _]:

import glob
glob.glob('/some/path_to/directory_1/and_to/directory_2'.replace('_', '[ _]'))

Note that this will fail if your path contains the character [. You can fix this by first replacing [ with [[].

like image 171
Mark Byers Avatar answered Oct 03 '22 07:10

Mark Byers