(* Wolfram Language offers excellent support for string formatting.
Here are some examples of common string formatting tasks. *)
(* Define a custom data structure *)
point[x_, y_] := <|"x" -> x, "y" -> y|>
(* Create an instance of our point structure *)
p = point[1, 2];
(* Basic formatting *)
Print["struct1: ", p]
(* Include field names *)
Print["struct2: ", ToString[p, InputForm]]
(* Print the full expression *)
Print["struct3: ", ToString[FullForm[p]]]
(* Print the type *)
Print["type: ", Head[p]]
(* Formatting booleans *)
Print["bool: ", ToString[True]]
(* Formatting integers *)
Print["int: ", ToString[123]]
(* Binary representation *)
Print["bin: ", IntegerString[14, 2]]
(* Character corresponding to integer *)
Print["char: ", FromCharacterCode[33]]
(* Hexadecimal encoding *)
Print["hex: ", IntegerString[456, 16]]
(* Formatting floats *)
Print["float1: ", NumberForm[78.9, {Infinity, 6}]]
(* Scientific notation *)
Print["float2: ", ScientificForm[123400000.0, 6]]
Print["float3: ", ScientificForm[123400000.0, 6, NumberFormat -> (Row[{#1, "E", #3}] &)]]
(* Basic string printing *)
Print["str1: ", "\"string\""]
(* Quote strings *)
Print["str2: ", ToString["\"string\"", InputForm]]
(* Hexadecimal representation of string *)
Print["str3: ", StringJoin[IntegerString[ToCharacterCode["hex this"], 16, 2]]]
(* Print memory address (not directly available in Wolfram Language) *)
Print["pointer: ", "N/A"]
(* Controlling width for integers *)
Print["width1: |", StringPadLeft[ToString[12], 6], "|", StringPadLeft[ToString[345], 6], "|"]
(* Controlling width and precision for floats *)
Print["width2: |", StringPadLeft[ToString[NumberForm[1.2, {6, 2}]], 6], "|",
StringPadLeft[ToString[NumberForm[3.45, {6, 2}]], 6], "|"]
(* Left-justified width for floats *)
Print["width3: |", StringPadRight[ToString[NumberForm[1.2, {6, 2}]], 6], "|",
StringPadRight[ToString[NumberForm[3.45, {6, 2}]], 6], "|"]
(* Right-justified width for strings *)
Print["width4: |", StringPadLeft["foo", 6], "|", StringPadLeft["b", 6], "|"]
(* Left-justified width for strings *)
Print["width5: |", StringPadRight["foo", 6], "|", StringPadRight["b", 6], "|"]
(* Formatting and returning a string *)
s = StringForm["sprintf: a ``", "string"];
Print[s]
(* Writing to stderr (approximation) *)
WriteString["stderr", StringForm["io: an ``\n", "error"]]