2

If I have a input line such as

userInput = input("Enter stuff: ").split()

which returns a list split by spaces.

How would I go about getting this to keep quoted text as a single item in the list?

eg. If I input hello "where are you?"

I want to get a list with ['hello', 'where are you?'] instead of ['hello', '"where', 'are', 'you?"']

Currently I am using a for loop to add the quoted text back together but I was hoping for a sleeker way.

userInputString = ""
for x in userInput[1:]:
    userInputString = userInputString + x + " "
userInputString = userInputString[1:-2] #remove the quotes and the last space
ThatsNotMyName
  • 572
  • 2
  • 8
  • 24
  • There are a few options for this including using a regex or for loop over list and build a second data structure that looks for double quotes for linking words - what have you tried? – LinkBerest Sep 19 '16 at 23:42
  • Ahh, I was using a for loop to put the quoted text back together but was hoping for a sleeker way. I'll edit that into the question. – ThatsNotMyName Sep 19 '16 at 23:50
  • Honestly, this question is pretty broad (there are a lot of methods for doing this): beyond the for loop [two are shown here](http://stackoverflow.com/questions/19933532/splitting-sentences-with-nltk-while-preserving-quotes) – LinkBerest Sep 20 '16 at 00:14
  • Just added the current method that works for me, the input will only be a single world followed by the quoted text. – ThatsNotMyName Sep 20 '16 at 00:31

2 Answers2

0

You can use:

>>> s = 'hello "where are you?"'
>>> s.split('"')
['hello ', 'where are you?', '']

And to avoid last empty space, better use a list comprehension:

>>> [item for item in s.split('"') if item]
['hello ', 'where are you?']
Jisson
  • 51
  • 7
0

Use shlex.split to use shell style splitting, which is quote sensitive:

>>> s = 'hello "where are you?"'
>>> shlex.split(s)
['hello', 'where are you?']
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271