Learn Julia · 6/15

Strings & Text Manipulation

7 min read

Strings & Text Manipulation 🧵

Welcome to the wonderful world of strings in Julia! You've been working with numbers and logic, which are the solid bricks and mortar of your programs. Now, it's time to add the friendly welcome mat and the fancy address plaque—the text! In programming, we call text "strings," and they are essential for communicating with users, handling data, and making your programs understandable.

Imagine you're building a robot assistant. You need it to understand commands like "fetch the newspaper" and to report back with messages like "I have retrieved the newspaper." This is where strings come in. They are the language your robot (and your program) uses to interact with the world.


1. String Basics and Interpolation 💬

The Problem: You need a way to store and use text in your program. How do you represent a simple sentence or even a single word?

The Solution: In Julia, you create strings by wrapping your text in double quotes ("). It's that simple!

julia
"Hello, Julia!"

For longer text that spans multiple lines, you can use triple double quotes ("""). This is great for writing longer messages or embedding chunks of text directly in your code.

julia
"""
This is a multi-line string.
It's perfect for when you have a lot to say!
"""

A Fun Fact: Julia strings are immutable, which means that once you create a string, you can't change it. If you want to modify a string, you actually create a new one. Think of it like a published book; you can't just go in and change the words. You have to print a whole new edition!

String Interpolation: Bringing Your Strings to Life ✨

The Problem: You often need to mix static text with the values of your variables. For example, you might want to greet a user by their specific name. How can you easily combine a string with a variable's value?

The Solution: Julia has a fantastic feature called string interpolation. It's a fancy term for a simple idea: embedding variables and expressions directly into a string. You do this with the $ symbol.

Imagine you have a variable for a user's name:

julia
name = "Alice"

To include this name in a greeting, you can "interpolate" it into the string:

julia
greeting = "Hello, $name!"
println(greeting)

This will print:

autohotkey
Hello, Alice!

This is much cleaner than manually piecing the string together. You can even perform calculations inside a string by wrapping the expression in parentheses after the $.

julia
x = 5
y = 10
println("The sum of $x and $y is $(x + y).")

This will print:

apache
The sum of 5 and 10 is 15.

If you ever need to use a literal dollar sign, just put a backslash \ before it.

julia
println("I have \$100 in my account.")

Under the Hood: When you use string interpolation, Julia is smart. It rewrites your interpolated string into a call to the string() function, which efficiently combines all the parts.


2. String Operations: Concatenation, Splitting, and Joining ✂️🔗

The Problem: You have pieces of text, and you need to combine them or break them apart in various ways. For instance, you might get a user's full name as "First Last" and need to separate the first and last names.

The Solution: Julia provides simple and powerful functions for these common tasks.

Concatenation: Sticking Strings Together

This is the act of joining strings. In Julia, you can use the * operator or the string() function.

julia
first_name = "John"
last_name = "Doe"

# Using the * operator
full_name = first_name * " " * last_name
println(full_name) # Output: John Doe

# Using the string() function
full_name_alt = string(first_name, " ", last_name)
println(full_name_alt) # Output: John Doe

Industry Practice: While both methods work, using string interpolation ("$(first_name) $(last_name)") is often the most readable and preferred way to combine strings in Julia.

Splitting: Breaking Strings Apart

The split() function is your go-to tool for breaking a string into an array of substrings based on a delimiter.

Imagine you have a comma-separated list of items:

julia
items_str = "apples,bananas,cherries"
items_array = split(items_str, ",")
println(items_array)

This will produce:

css
["apples", "bananas", "cherries"]

If you don't provide a delimiter, split() will use whitespace as the default separator.

Joining: Putting the Pieces Back Together

The join() function does the opposite of split(). It takes an array of strings and combines them into a single string, with a specified separator.

julia
items_array = ["apples", "bananas", "cherries"]
items_str = join(items_array, ", ")
println(items_str)

This will output:

autohotkey
apples, bananas, cherries

A Fun Exaggeration: If you tried to manually join a million-item array with a for loop, you'd be waiting long enough for your pet snail to win a marathon. join() is incredibly efficient for this!


3. Regular Expressions in Julia 🕵️‍♀️

The Problem: Sometimes you need to find patterns in text, not just exact words. For example, how would you find all the email addresses in a large document?

The Solution: Regular Expressions (often shortened to "regex") are a powerful tool for pattern matching in text. Julia has excellent built-in support for regular expressions, using the PCRE2 library.

You create a regular expression in Julia by prefixing a string with r.

julia
re = r"^\s*(?:#|$)"

Let's break down some common regex patterns:

  • \d: Matches any digit.
  • \w: Matches any word character (letters, numbers, and underscore).
  • \s: Matches any whitespace character.
  • +: Matches one or more of the preceding character.
  • *: Matches zero or more of the preceding character.
  • .: Matches any character except a newline.

Finding a Match

To check if a pattern exists in a string, you can use the occursin() function.

julia
email_pattern = r"\w+@\w+\.\w+"
text = "You can reach me at [email protected] or [email protected]"

println(occursin(email_pattern, text)) # Output: true

To get more details about the first match, use the match() function. It returns a RegexMatch object, or nothing if no match is found.

julia
m = match(email_pattern, text)
if m !== nothing
    println("Found a match: ", m.match)
end

Output:

golo
Found a match: alice@example.com

You can extract the matched substring, captured groups, and the offset of the match.

Finding All Matches

To find all occurrences of a pattern, use eachmatch().

julia
for m in eachmatch(email_pattern, text)
    println("Found: ", m.match)
end

Output:

avrasm
Found: [email protected]
Found: bob@test.org

A Real-World Scenario: Imagine you're a data scientist analyzing customer feedback. You could use a regular expression to quickly find all mentions of product codes (e.g., PROD-12345) within thousands of reviews.


4. Parsing Numbers from Strings and Formatting Text 🔢➡️🔠

The Problem: You often receive data as text, but you need to work with it as numbers. Conversely, you might have numbers that you need to present in a nicely formatted string.

The Solution: Julia provides easy ways to convert between strings and numbers.

Parsing Numbers from Strings

The parse() function is the primary tool for converting a string to a number. You need to tell it the type of number you expect.

julia
str_int = "123"
num_int = parse(Int, str_int)
println(num_int)       # Output: 123
println(typeof(num_int)) # Output: Int64

str_float = "3.14"
num_float = parse(Float64, str_float)
println(num_float)       # Output: 3.14
println(typeof(num_float)) # Output: Float64

If parse() can't convert the string, it will throw an error. For situations where you're not sure if a string is a valid number, you can use tryparse(), which returns nothing on failure instead of throwing an error.

Industry Practice: When dealing with user input or data from external sources, it's generally safer to use tryparse() to handle potential errors gracefully.

Formatting Text

While Julia's println() and string interpolation handle many basic formatting needs, for more complex scenarios like controlling the number of decimal places or padding with spaces, you can use macros from the Printf standard library.

First, you need to bring it into your scope:

julia
using Printf

Then you can use the @printf macro for C-style formatted printing:

julia
pi_approx = 3.1415926535
@printf "The value of pi is approximately %.2f\n" pi_approx

Output:

apache
The value of pi is approximately 3.14

The @sprintf macro works similarly but returns a formatted string instead of printing it.

julia
formatted_pi = @sprintf "%.4f" pi_approx
println("Pi formatted to 4 decimal places: $formatted_pi")

Output:

apache
Pi formatted to 4 decimal places: 3.1416

References for Extra Reading 📚

Challenge

Challenge: Data Log Processor

You are tasked with writing a Julia function to process a raw, multi-line string containing log data. Your function must parse each line, perform a calculation, and reformat the data into a standardized summary report.

Requirements:

  1. Define a function process_log_data that accepts a single String argument named log_data.
  2. The input log_data is a multi-line string where each line represents a user record.
  3. Each record line consists of key-value pairs separated by semicolons (;). The relevant pairs are ID, Name, and Value.
  4. Your function should perform the following steps:
    a. Split the input string into individual lines.
    b. For each line, extract the string values for Name, ID, and Value.
    c. Parse the ID into an Int and the Value into a Float64.
    d. Calculate an adjusted_value by increasing the original Value by 7.5%.
    e. Create a new summary string for each record using the precise format: "[PROCESSED] User: <Name> (ID: <ID>) - Adjusted Value: <adjusted_value>". The adjusted value must be formatted to exactly two decimal places.
    f. After processing all lines, join the individual summary strings into a single string, with each summary separated by a newline character (\n).
  5. The function must return this final, combined string.

Hint: You may need to use the Printf standard library for precise numeric formatting.

Expected result

The processed_output variable should hold a single multi-line string. Each line in the string must match the specified format exactly, including spacing and punctuation. The numeric values must be calculated and formatted correctly to two decimal places.

nix
[PROCESSED] User: Alice (ID: 101) - Adjusted Value: 268.75
[PROCESSED] User: Bob (ID: 102) - Adjusted Value: 188.66
[PROCESSED] User: Charlie (ID: 103) - Adjusted Value: 344.81
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.