26

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 . '!'

2 Answers 2

33

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'.
2
  • Is it possible to include ' inside a single-quoted string?
    – Tom Hale
    Sep 28, 2016 at 2:41
  • 5
    @TomHale. Yes it is. Double it. -> 'foo''bar', or use both kind of quotes: 'foo'."'".'bar' Sep 28, 2016 at 7:40
2

In the Vim documentation a double quoted string and a single quoted string are both referred to as a string constant.

  • double-quoted :help expr-string
  • single-quoted :help literal-string

The help lists the difference for single quotes as:

This string is taken as it is.  No backslashes are removed or have a special
meaning.  The only exception is that two quotes stand for one quote.

Because I'm a Javascript developer I see quite a lot of similarity with the single and double quoted strings there - but obviously string contactenation is done with . in Vimscript.

Further information from Learn Vimscript the Hard Way - Strings that has the default kind of string is a double quoted strings with a special section for Literal Strings

Vim also lets you use "literal strings" to avoid excessive use of escape sequences.

...

We'll revisit literal strings when they become most useful, later in the book (when we dive into regular expressions).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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