In python to see if a string is non-empty, I'll do something like:
if STRING_VAR:
...
However, in vim a string doesn't really give a real truth-value when used directly. Is there a suggested way to evaluate the truthiness of a string? Usually I will use either:
if (STRING_VAR != "")
...
Or:
if (len(STRING_VAR) != 0)
...
What's the suggested/cleanest way to do this?
However, in vim a string doesn't really give a real truth-value when used directly.
If programming were a religion then the Pythonistas would become zealots ;-) Say, for a C programmer the real truth is a number, and for an assembly one it's totally unaddressable and the Strings do not exist at all. So how can you speak of a "real truth" then?
VimScript is partially modelled after C and AWK. In particular, :if
accepts only numeric values (zero is false, non-zero is true) including those "convertible" to numbers, such as... Strings. However, String-to-Number conversion is done like with :h str2nr()
. And so :if "hello world"
is legal but false.
So you'll probably want :if empty(var)
instead.
Note however that :h empty()
accepts any Vim type. Usually this is quite good, but on some rare occasions you prefer :if len(var)
or :if strlen(var)
.
The difference between :h len()
and :h strlen()
is that strlen()
accepts Strings, while len()
also accepts Lists and Dictionaries.
Still note that :echo strlen(0)
is 1
, as Numbers are auto-converted to Strings anyway. And so if you want to check simultaneously that 1) foo
has type of String, and 2) foo
is empty then you have to write :if foo is# ''