pic
Personal
Website

2d. Strings

PhD in Economics

Introduction

This section provides a concise overview of standard types for text representation, covering the fundamental concepts of introducing text and string interpolation. Although in-depth string analysis isn't necessary, understanding these basic principles are essential for using Julia effectively.

Characters

The Char type is used to represent individual characters. As it supports Unicode characters, it encompasses not only numbers and letters, but also a wide range of symbols. A character x is introduced by using the syntax 'x', as shown below.

Code

# x equals the character 'a'
x = 'a'

# 'Char' allows for Unicode characters
x = 'Îē'
y = '🐒'

Notice that characters necessarily must be enclosed in single quotes ' ', or otherwise Julia will interpret the expression as a variable. This holds even for symbols like 🐒.

Code

# any character is allowed for defining a variable
🐒 = 2          # 🐒 represents a variable, just like if we had defined x = 2

y  = 🐒         # y equals 2
z  = '🐒'       # z equals the character 🐒

Strings

We'll rarely use the type Char directly. Instead, we'll work with the type String, which is an ordered collection of characters that can represent text.

Strings can be defined through either double quotes " " or triple quotes """ """. The latter is particularly convenient for handling newlines, such as when the text has to span multiple lines. [note] For more on the differences between double and triple quotes, see here

Code

x = "Hello, beautiful world"

x = """Hello, beautiful world"""

String Interpolation

String interpolation allows you to embed expressions or variables within a string, and then evaluate those expressions or replace the variables with their values.

To interpolate an expression into a string, you simply prefix it with the $ symbol. If the expression contains spaces, you'll need to enclose it in curly braces, like $(). Both cases are exemplified below.

number_students = 10


x = "There are $(number_students) students in the course"

Output in REPL
julia>
x
"There are 10 students in the course"

number_matches  = 50
goals_per_match = 2

x = "Last year, Messi scored $(number_matches * goals_per_match) goals"

Output in REPL
julia>
x
"Last year, Messi scored 100 goals"