0

Using Vim, in a file containing strings on successive lines:

bear
fox
jackie chan

What's a good, repeatable way to make a python list of strings:

['bear', 'fox', 'jackie chan']

Tried a kludgy sequence of regexs over the range (such as :1,3s/^/'/, :1,3s/$\n/', /, followed by pesky hand edits.

5 Answers 5

2
ggcG                           change the whole buffer

<C-r>=string(split(@"))<CR>    insert a string representation of
                               the content of the unnamed register

<Esc>                          leave insert mode
Sign up to request clarification or add additional context in comments.

2 Comments

Appears to yield ['bear', 'fox', 'jackie', 'chan'] not ['bear', 'fox', 'jackie chan']
@jwco You can use a more sophisticated regex for the split, ^\s*\|\s*\n\s*. Here it is in a command: command! -range=% ToList execute "normal! ".(<line2>-<line1>+1)."cc\<c-r>=string(split(@@,'^\\s*\\<bar>\s*\\n\\s*'))\<cr>"
1

You can use multiple substitutions and :join to accomplish this:

:%s/^\s*\zs.*/'&',/|'[,']j|s//[&]/

This will yield:

['bear', 'fox', 'jackie chan',]

Personally I like the trailing comma, but you can remove it with another substitution or :normal command:

%s/^\s*\zs.*/'&',/|'[,']j|s//[&]/|s/,]$/]
%s/^\s*\zs.*/'&',/|'[,']j|exe "norm! $x"|s//[&]/

For more help see:

:h :s
:h \zs
:h :j
:h :norm
:h :exe
:h :bar
:h :range
:h '[

Comments

1

I'd go with a macro:

qq0i'^[$a',^[

This wrap the line into a '...',

You can select all your lines and apply the macro with:

:normal! @q

Then you can add a [ before the first line, a ] after the last one and

vipJ

Comments

0

Solution

:s/\(.*\)\n\(.*\)\n\(.*\)/['\1', '\2', '\3']/

1 Comment

That only works for eactly 3 elements. This does not scale well to 4, 5 or more elements.
0

With my Join plugin (https://github.com/sk1418/Join), you can join lines with separator. For the given example, you can do:

:%s/^\|$/'/g|%J ','

then manually add the [' and '] to BOL and EOL

or just

:%J "','"

then manually add [' and '] to BOL and EOL

1 Comment

Like a general solution. However, slight aversion to manually adding brackets

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.