Strings
Mix.install([
{:kino, github: "livebook-dev/kino", override: true},
{:kino_lab, "~> 0.1.0-dev", github: "jonatanklosko/kino_lab"},
{:vega_lite, "~> 0.1.4"},
{:kino_vega_lite, "~> 0.1.1"},
{:benchee, "~> 0.1"},
{:ecto, "~> 3.7"},
{:math, "~> 0.7.0"},
{:faker, "~> 0.17.0"},
{:utils, path: "#{__DIR__}/../utils"}
])
Navigation
Setup
Ensure you type the ea
keyboard shortcut to evaluate all Elixir cells before starting. Alternatively you can evaluate the Elixir cells as you read.
Strings
A string is any sequence of characters contained within two double quotes ""
.
A character is any single number, letter, or symbol.
"T" # letters
"t" # letters
"1" # numbers
"1.2" # numbers
"&" # symbols
"_" # symbols
You can visualize a string as characters joined together by strings. Strings can be a single character, no characters, or many characters!
flowchart LR
S --- T --- R --- I --- N --- G
Strings can contain single quotes and other symbols such as !@#$%^&*()_+-=';:
and more.
"!@#$%^&*()_+-=';:"
They are useful for representing all kinds of information as text.
Your Turn
In the Elixir cell below, create a string "Hello, world!"
. This is a rite of passage for every
programmer.
String Operators
String operators allow us to manipulate strings.
The <>
operator joins two strings together. Joining strings together is called string concatenation.
"hello, " <> "world."
Only strings can be concatenated together using the <>
operator. You’ll notice concatenating 1
causes an error expected binary argument in <> operator but got 1
"hello" <> 1
Your Turn
In the Elixir cell below, use string concatenation to join "Hi, "
and the name of one
of your classmates.
So "Peter"
would be come "Hi, Peter."
.
Replace nil
with your answer.
answer = nil
Utils.feedback(:string_concatenation, answer)
String Interpolation
Using #{}
, We can also interpolate values in strings. Essentially, this means we can evaluate code inside of
a string. The code you want to interpolate inside of the string
goes between the curly braces {}
.
So we can evaluate 4 + 4
, which equals 8
inside a string.
"I have #{4 + 4} apples."
String interpolation is often useful when your string has many computed values or tricky punctuation. Otherwise, it’s easy to make mistakes.
Notice that there’s a grammar mistake below that could easily be missed when using string concatenation.
"I have" <> "8" <> "apples"
Your Turn
In the Elixir cell below, use string interpolation to say I have #{X - 1} classmates.
. Where
X is the number of people in your cohort including yourself.
Replace nil
with your answer.
answer = nil
Utils.feedback(:string_interpolation, answer)
Commit Your Progress
Run the following in your command line from the project folder to track and save your progress in a Git commit.
$ git add .
$ git commit -m "finish strings section"