Formatting of Strings in Julia
Last Updated :
21 May, 2024
Julia is a high-level language developed by people at Massachusetts Institute of Technology. It is an open-source, high-performance language. It has a simple syntax like Python but has speed and performance of C.
String formatting is the process of evaluating a string literal using string interpolation (filling unknown values between known values), it yields a result in which placeholders are replaced with their corresponding values.
For example:
word="article"
@printf("This is an %s",word)
The upper code will replace '%s' with the value of word and the output will be:
This is an article
Most current languages provide different types of format specifiers and different formatting functions as well. In Julia, there are format specifiers somewhat similar to C:
- %c: a single character (letter, number, special symbol)
- %s: string (a combination of characters)
- %d: integer (any whole number (not a fraction))
- %f: float (numbers having floating decimal points)
- %.nf: float restricted up to n decimal places
- %e: scientific representation of a float number
There are 2 ways to format a string in Julia.
Method 1: Using Printf Library
Printf is a standard library in Julia that is included by following the syntax:
using Printf
Julia uses printf() function similar to C, in order to format strings. Here, we print using the macro @printf.
Printing different data types
Characters: In the following code, we are storing a single letter 'c' in the variable named 'character'. The character variable is then printed using '%c' format specifier as its data type is char. To make the specifier functionality more understandable another variable 'character2' with the same data type (character) is used.
Julia
using printf
character = 'c';
@printf("the letter is %c", character);
character2 = 'a';
@printf("the two letters are %c and %c",
character, character2);

In the output, it can be clearly seen that %c is replaced with the value of the character variable in the first printf statement and both %c are replaced with values of character and character2 in the second printf statement.
Strings: In the following example a string 'GeeksforGeeks' is stored in a variable 's' and is printed using the '%s' specifier and printf. To make this code more understandable, another string S2 is added whose value is 'I love', and both the strings are printed together making it 'I love GeeksforGeeks'.
Julia
# Loading Library
using Printf
# Creating String
s = "GeeksforGeeks";
# Formatting first string
@printf("welcome to %s", s);
# Creating second string
s2 = "I love";
# Formatting both strings
@printf("%s %s", s2, s);

In the output, you can see how in the first printf statement %s is replaced with the value of s. Similarly, in the second printf statement, both %s are replaced with s2 and s.
Integers: In the code below, we have defined a variable named integer as 33. We have then printed it using '%d' specifier. Similarly, we have defined one more variable integer2 and have set its value to 42. In the second printf statement, we have printed the sum of both these numbers.
Julia
using Printf
integer = 33;
@printf("the value is %d",integer);
integer2 = 42;
@printf("the sum is %d + %d = %d",
integer, integer2,
integer + integer2);

In the output, look at how '%d' is replaced with the value of integer in the first printf statement. And, in the second printf statement %d,%d and %d are replaced with integer, integer2, and integer+integer2.
Float: In the code below, we have declared a variable 'floatvalue' and set it to 0.08. We have then printed this value using '%f' specifier. Then we initialized one more variable 'floatvalue2' and set it to 1.92. In the second printf statement, we have printed sum of both these values using specifiers '%d' and '%f'.
Julia
using Printf
floatvalue = 0.08;
@printf("the floating point value is %f",
floatvalue);
floatvalue2 = 1.92;
@printf("the value of %f + %f = %d",
floatvalue, floatvalue2,
floatvalue + floatvalue2);

You can see how %f is replaced with 0.08 in the first output and %f,%f, and %d are replaced with 0.08, 1.92, and 2 respectively. (Notice how we used '%d' to print this sum and obtained integral value of the sum if you wish to obtain the float value of sum you can use '%f' specifier.)
Floating-point values restricted to 2 decimal places: Suppose we have the value of pi and we want to display it, but instead of displaying its whole value we just want to print the value '3.14' i.e. the value should be restricted to 2 decimal places. For this we use %.nf (n being the limit).
Julia
using Printf
floatvalue = 20.3658;
@printf("the value of float restricted to 2 decimal places %.2f",
floatvalue);

In this output, you can see how 20.3658 is printed as 20.37 as it is rounded up to 2 decimal places.
Scientific representation of a floating-point number: You can print out the scientific representation of a floating-point number using '%e' specifier. It is usually used to represent very large or very small numbers.
Julia
using Printf
floatvalue = 20.3658;
@printf("scientific representation of the floatvalue is %e",
floatvalue);

In this output, notice how 'floatvalue' (20.3658) is displayed as 2.063580e+01. This happened because we used '%e' specifier and it printed out its scientific representation.
Method 2: Using Formatting.jl Package
Formatting.jl is an open-source Julia package that was made to provide python like formatting to Julia.
Installation Command - Pkg.add("Formatting")
We can use printfmt or printfmtln for formatted printing. Additionally, "fmt" and "format" can be used to format string values.Â
Example: Printing different data types
In this method, formatting is done similarly to that in python. Format specifiers are put inside curly braces {} and '%' symbol is replaced with ':' Â (look in the code below).
Julia
using Formatting
# to print a string
site = "GeeksforGeeks";
printfmt("Welcome to {:s}", site)
# to print a single character
c = 'a';
printfmt("Character is {:c}", c)
# to print an integer
num = 40;
printfmt("Integer is {:d}", num)
# to print a float value
floatnum = 178.33987;
printfmt("Float value is {:f}", floatnum)
# to print a float value
# restricted to 2 decimal places
printfmt("Restricted to 2 decimal places {:.2f}",
floatnum)
# to print a float value
# in scientific representation
printfmt("Scientific representation {:e}",
floatnum)
Output

In the output, you can see how {:c}, {:s}, {:d}, {:f}, {:e}, {:.2f}, are replaced with characters, strings, integers, floating-point numbers, scientific representations and floating point numbers restricted to 2 digits after decimal, respectively.
Similar Reads
String concatenation in Julia
String concatenation in Julia is a way of appending two or more strings into a single string whether it is character by character or using some special characters end to end. There are many ways to perform string concatenation. Example:Â Input: str1 = 'Geeks' str2 = 'for' str3 = 'Geeks' Output: 'Gee
2 min read
Strings in Julia
Strings in Julia are a set of characters or a single character that is enclosed within double quotes(" "). It is a finite sequence of characters. Julia allows extracting elements of a string to form multiple substrings with the use of square brackets([ ]). Creating a String Strings in Julia can be c
6 min read
Format Specifiers in Julia
Format Specifiers are used to format the Input and Output of a Programming language. It tell the compiler about the data type of the Input that is being passed to it. Julia contains a package Printf and using its macro @printf takes input string value to be formatted and accepts parameters as variab
4 min read
Sorting of Strings in Julia
Sorting of strings in Julia means that now we are sorting the characters of the string. In Julia, this can easily be achieved with the basic logic of getting each character of the string into a separate array and sorting the array. Lastly joining the array together to get the sorted array. Major tas
4 min read
Taking Input from Users in Julia
Reading user input is a way of interaction between the program and the user. User inputs are necessary in case of testing a piece of code with varying and legitimate inputs. Reading user inputs from console in Julia can be done through inbuilt I/O methods like : readline() readlines() Using readline
3 min read
String to Number Conversion in Julia
Julia is a flexible, dynamic, and high-level programming language that can be used to write any application. Also, many of its features can be used for numerical analysis and computational science. Julia is being widely used in machine learning, visualization, and data science. Julia allows type con
3 min read
Compare two strings in Julia - cmp() Method
The cmp() is an inbuilt function in julia which is used to return 0 if the both specified strings are having the same length and the character at each index is the same in both strings, return -1 if a is a prefix of b, or if a comes before b in alphabetical order and return 1 if b is a prefix of a,
2 min read
Storing Output on a File in Julia
Julia provides a vast library to store and save the output in multiple file formats. We can store the output in various forms such as CSV(comma-separated value) or in Excel or just simply a text file. Storing Data on Text FileUsing open() function In order to store the data in a text file, we need t
4 min read
try keyword - Handling Errors in Julia
Keywords in Julia are words that can not be used as a variable name because they have a pre-defined meaning to the compiler. 'try' keyword in Julia is used to intercept errors thrown by the compiler, so that the program execution can continue. This helps in providing the user a warning that this cod
2 min read
For loop in Julia
For loops are used to iterate over a set of values and perform a set of operations that are given in the body of the loop. For loops are used for sequential traversal. In Julia, there is no C style for loop, i.e., for (i = 0; i Syntax: for iterator in range statements(s) end Here, 'for' is the keywo
2 min read