-1

Every time I need to create a list of strings in python or another language with similar list syntax (and they more or less the same everywhere) I have to do the following.

# resulting expression
a = ('word1', 'word2', 'word3')

#cursor is between the parenthesis
a = (|)

type 'word1<ESC>a, etc for each word. I don't have to type single quote twice, because I'm using delimitmate, but I have to use esc to move cursor out of the quotes. There is a better way to do it. What if I would type

a = (word1 word2 word3)

instead and then use regex to surround all words inside parens with quotes and add comma after that? This would save me 3 key strokes for each word if I would remap this to some key. The problem is I don't know how to do this replacement via regex. So the best I've got so far is

:s/\v\((.*)\)/\=substitute(submatch(0) ....

The dots in the end is because I need to replace it with backreference in substitute, but I don't know how to do that.

  • If you do type the single quote twice, does it have the effect of moving the cursor to the other side of the auto-inserted quote? – alxndr Mar 26 '16 at 21:49
2
a = ('word1', 'word2', 'word3')

Technically, that's a tuple. :)

Now, for the substitute() command, it depends on what the strings can contain. If they don't contain any whitespace, you can match non-whitespace characters with \S:

:s/(\zs.*\ze)/\=substitute(submatch(0), '\S\+', "'&',", 'g')/

This will leave a trailing comma, which shouldn't be a problem. You could also use \w for word-characters, \i for characters allowed in identifiers, etc. I have modified your expression to leave out the parentheses in the matched text - they don't belong in the strings and complicating the second pattern for handling them is unnecessary.

Similarly, you can use a delimiting character that won't appear in the strings (think CSV), then use all-but-that-character in the substitute() pattern (, and [^,], for example).

1

You could also use a macro:

Once you have:

a = (word1 word2 word3)

Go on the ( character with for example 0f(

Then record this macro: qqwi'<Esc>ea',<Esc>q

  • qq start recording in register q
  • w go to the next word
  • i'<esc> insert a ' before the word and leave insert mode
  • e go to the end of the word
  • a',<Esc> append a ', after the word and leave insert mode
  • q stop recording the macro

You can then replay the macro as many time as you have words in the list: here it would be 2@q.

This also leave would with a trailing coma that you'll have to remove.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.