Lesson 15. String conversions
In Lesson 11, we have talked very briefly about the str function and how it enables us to convert data into string and to concatenate string. In this Lesson, we are going to explore more aspects of the conversion between data and string. In particular, we will learn how to concatenate strings and data, how to format numbers and how to handle the conversion in the other direction, from a string into data.
After reading this lesson, you will be able to:
- Concatenate strings
- Convert data into string
- Build strings made of strings and data
- Format numbers
- Convert strings into data
15.1 String concatenation with str
Let’s start with a task that might remind you the famous "Hello, World!" challenge: Write a function named hello that receives a name as argument and returns a string with the following structure: "Hello, <name>!". For instance, calling (hello "John") should return "Hello, John!" and (hello "Diana") should return "Hello, Diana!".
For that purpose, we need the ability to concatenate strings: the str function is what we use in Clojure for string concatenation: str receives any number of arguments and when the arguments are strings, str simply concatenates them. We will see later how str deals with arguments that are not strings.
Let’s see a couple of examples:
user=> (str "Clojure " "rocks!") "Clojure rocks!" user=> (str "Clojure " "is " "awesome.") "Clojure is awesome."
When we pass a single string to str, it returns it: