18

What is the difference between single and double quoted strings?

Is there a way to get a variable expanded inside a string, or do they always need to be joined like: 'Hello, ' . s:name . '!'

23

The only difference between single and double quoted string is related to backslash. To display special characters like newline, bells, tabs, etc, you need to use double-quotes -> "\n".

Within a single-quoted string, '\' is itself => '\n' is a two-characters string (a backslash + n). Within double quotes, you have to double it -> "\\", which makes them un-practical to define regexes.

Regarding string expansion, you have a few choices:

  • 'Hello, ' . s:name . '!'
  • join(['Hello, ', s:name, '!'], '') -- which we never use
  • printf('Hello %s!', s:name)
  • lh#fmt#printf('Hello %1!', s:name) -- from lh-vim-lib, when we don't want to know about types, and when we don't need to format fields, but when we want to use formats like: 'Hello %1. How are you doing %1 this %2'.
  • Is it possible to include ' inside a single-quoted string? – Tom Hale Sep 28 '16 at 2:41
  • 2
    @TomHale. Yes it is. Double it. -> 'foo''bar', or use both kind of quotes: 'foo'."'".'bar' – Luc Hermitte Sep 28 '16 at 7:40

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.