简体   繁体   中英

Determine if string in input is a single word in Python

a brain dead third party program I'm forced to use determines how to treat paths depending if the input supplied is a single word, or a full path: in the former case, the path is interpreted relative to some obscure root directory.

So, given that the input can be a full or relative path, or a single word (including underscores and dashes, but not spaces), I'm wondering how to write a function that determines if the input is a single "word" as defined above.

For example:

  • "Public_345" would classify as valid "word"
  • "/home/path/to/something" would obviously be not
  • "Foo bar" would also not be considered a valid "word"

As string methods are not OK, I am wondering if it would be possible to use regular expression. Initially I thought up of something like this:

match = re.compile(r"[\w-]+")
word = "abdcde_-4"
if len(re.findall(match, word)) == 1:
    print "Single word"

It does feel extremely ugly, however, and I'm pretty sure it doesn't catch corner cases. Are there (much) better solutions around there?

You could tweak your regex to match the whole input string so that you don't have to count the matches. Ie

if re.match(r'\A[\w-]+\Z', word):
  print "Single word"

(compile the regex if you feel so inclined)

\\A and \\Z match the beginning and end of the input string, respectively. So, if your word contains other data in it besides the path, then the above approach does not work.

>>> r="Foo bar".split()
>>> if len(r) != 1: print "not ok"
...
not ok
>>> if "/" in "/home/path/to/something":
...   print "ok"
...
ok

Just check the string and see if it contains a ' ' (space) or an '\\' (path separator). If it does, then it's not a "single word".

Check the os.path module. You can use os.path.abspath() to convert a given path into full path (if it is on the same system).

You can check with the following snippet if the string has any whitespace characters.

if(str.split()[-1] == str) return True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM