More About Strings

String Delimiters

  • Double quotes (”…”) or single quotes (’…’)

  • No difference

    'spam eggs'
    
    'spam eggs'
    
    "spam eggs"
    
    'spam eggs'
    
  • Single quote (') embedded as literal character inside a string delimited with single quotes ⟶ escaping needed

    'doesn\'t'
    
    "doesn't"
    
  • Alternative: choose double quote as string delimiter

    "doesn't"
    
    "doesn't"
    
  • Or, the other way around

    '"Yes," he said.'
    
    '"Yes," he said.'
    
  • No way out though if both double and single quotes need to be part of a string

    '"Isn\'t," she said.'
    
    '"Isn\'t," she said.'
    

Escape Sequences

  • Newline, embedded in string

    print('first line\nsecond line')
    
    first line
    second line
    

More (but not all) escape sequences

Escape character

Meaning

\n

Linefeed

\r

Carriage return

\t

Tab

\b

Backspace

\0

ASCII 0

\130

ASCII dec. 88 (‘X’) in octal

\x58

ASCII dec. 88 (‘X’) in hexadecimal

Raw Strings

  • Unwanted escaping (Doze pathnames) …

    print('C:\some\name')
    print(r'C:\some\name')
    
    C:\some
    ame
    C:\some\name
    
  • Unwanted escaping (regular expressions)

    import re
    regex = re.compile(r'^(.*)\.(\d+)$')
    

Multiline Strings

Escaping newlines is no fun

print("""\
Bummer!
You messed it up!
""")
Bummer!
You messed it up!

will produce …

Bummer!
You messed it up!
  • Note how the initial newline is escaped ⟶ line continuation

  • Newline must immediately follow backslash

More String Tricks

  • String literal concatenation

    'Hello' ' ' 'World'
    
    'Hello World'
    
  • String literal concatenation (multiple lines)

    ('Hello'
    ' '
    'World')
    
    'Hello World'