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}}
StringSplitwith no separator splits on whitespace.StringRifflejoins a list with a separator.StringPositiongives 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 withToStringfirst.ToExpressionturns 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—StringJoincomplains that5is not a string. Use"Total: " <> ToString[5], orPrint["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.