Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove surrounding quotes inside a String in Erlang?

Tags:

string

erlang

I am using epgsql to query a database, in Erlang. It returns string results including quotation marks surrounding them like this: "what_was_in_the_row". How can I remove these quotation marks before working with the result?

like image 626
HorseHair Avatar asked Jan 04 '23 02:01

HorseHair


1 Answers

the control format ~p (pretty print) keeps information about the type of the variables that are printed. You are printing a string, which is, in erlang, a standard integer list made of printable characters for example [101,102,103] is displayed as "efg" in the shell.

If you call io_lib:format("~p",[[101,102,103]])., you will get the result ["\"efg\""] which needs some explanation.

  • The surrounding brackets indicate a list, which is the return value type of io_lib:format/2,
  • then the first double quotes indicates another list that maybe a string, it is syntactic sugar, but it is not part of the result (I say maybe because any list that looks like a string will be displayed as a string with pretty print),
  • finally the \" is an escape sequence that represents the single character "

You can evaluate the length of each string to verify the difference:

  • 3 = length("efg").
  • 5 = length("\"efg\"").

If you want to get the string without the surrounding quotes, you must use the control format ~s

1> [Res] = io_lib:format("~s",[[101,102,103]]).
["efg"]
2> length(Res).
3
3> [Res] = io_lib:format("~s",[Res]).          
["efg"]

Of course, the last line shows that my example is stupid. With io_lib:format("~s ~s!",["Hello","world"]). or any more complex formatting, the result is of type chars(): a list of char() or chars().

like image 176
Pascal Avatar answered Mar 08 '23 10:03

Pascal