Get Started

Escape sequences

You might have been surprised at the output from the last part of the last exercise. How did you get two lines from one string, and how did you get that little globe? The key is the \.

A sequence in a string that starts with a \ is called an escape sequence and allows us to include special characters in our strings. You saw one escape sequence in the first exercise: \" is used to denote a double quote.

In "hello\n\U1F30D" there are two escape sequences: \n gives a newline, and \U followed by up to 8 hex digits sequence denotes a particular Unicode character.

Unicode is a standard for representing characters that might not be on your keyboard. Each available character has a Unicode code point: a number that uniquely identifies it. These code points are generally written in hex notation, that is, using base 16 and the digits 0-9 and A-F. You can find the code point for a particular character by looking up a code chart. If you only need four digits for the codepoint, an alternative escape sequence is \u.

When R comes across a \ it assumes you are starting an escape, so if you actually need a backslash in your string you'll need the sequence \\.

This is a part of the course

“String Manipulation with stringr in R”

View Course

Exercise instructions

  • Edit the string inside writeLines() so that it correctly displays (all on one line):

    To have a \ you need \\
    
  • Edit the string inside writeLines() so that it correctly displays (with the line breaks in these positions)

    This is a really 
    really really 
    long string
    
  • Try writeLines() with the string containing Unicode characters: "\u0928\u092e\u0938\u094d\u0924\u0947 \u0926\u0941\u0928\u093f\u092f\u093e". You just said "Hello World" in Hindi!

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Should display: To have a \ you need \\
writeLines("To have a \ you need \\")

# Should display: 
# This is a really 
# really really 
# long string
writeLines("This is a really really really long string")

# Use writeLines() with 
# "\u0928\u092e\u0938\u094d\u0924\u0947 \u0926\u0941\u0928\u093f\u092f\u093e"
___
Edit and Run Code