Skip to content
AgileLogics
6 min read

Strings

Prerequisites: Working with lists

A string is text in double quotes. Remember that results show strings without their quotes.

s = "Wolfram Language";
StringLength[s]
ToUpperCase[s]
StringTake[s, 7]
StringTake[s, -8]
StringReverse["hello"]
s <> "!"
16
WOLFRAM LANGUAGE
Wolfram
Language
olleh
Wolfram Language!

Splitting, joining, replacing

StringSplit["a,b,c", ","]
StringSplit["one two  three"]
StringRiffle[{"x", "y", "z"}, ", "]
StringReplace["cat hat", "at" -> "og"]
StringContainsQ["banana", "nan"]
StringCount["banana", "a"]
StringPosition["banana", "an"]
{a, b, c}
{one, two, three}
x, y, z
cog hog
True
3
{{2, 3}, {4, 5}}
  • StringSplit with no separator splits on whitespace.
  • StringRiffle joins a list with a separator.
  • StringPosition gives the start and end of each match.

Converting

ToString[42] <> " apples"
ToExpression["2 + 3"]
Characters["abc"]
ToCharacterCode["A"]
FromCharacterCode[72]
StringPadLeft["7", 3, "0"]
42 apples
5
{a, b, c}
{65}
H
007
  • <> joins only strings — convert numbers with ToString first.
  • ToExpression turns text into code and evaluates it.

Showing quotes

To see the quotes (or a string's exact contents), use InputForm:

{"a", "b"} // InputForm
{"a", "b"}

Common mistakes

  • "Total: " <> 5 — StringJoin complains that 5 is not a string. Use "Total: " <> ToString[5], or Print["Total: ", 5], which accepts anything.
  • Using single quotes — only double quotes make strings.

Practice

Turn "hello world" into "Hello World" by capitalizing the first letter of each word.

Show solution
StringRiffle[Capitalize /@ StringSplit["hello world"], " "]
Hello World

Capitalize uppercases the first letter; /@ applies it to each word (see "Pure Functions and Map"). Capitalize["hello world", "TitleCase"] is a shortcut.