More on Strings

Advanced String Syntax

Strings can begin and end with either single quote ' ' or double quotes " "

Escape Characters

Escape characters \ let you put quotes and other characters that are hard to type inside strings

In [1]:
# 'That is Alice's cat' # SyntaxError
In [2]:
'That is Alice\'s cat'
Out[2]:
"That is Alice's cat"
Escape Character Prints as
\' Signle quote
\" Double quotes
\t Tab
\n Newline (line break)
\ Backslash

Raw Strings

Raw strings r' ' will literally print any backslash \ in the string and ignore escape characters

In [3]:
r'That is Carol\'s cat.'
Out[3]:
"That is Carol\\'s cat."
In [4]:
print(r'That is Carol\'s cat.')
That is Carol\'s cat.

Multiline Strings with Triple Quotes

Multiline strings start and end with three quotes ''' or """, and can span multiple lines.

In [5]:
print("""Dear Alice,
Eve's cat has been arrested for catnapping
Sincerely,
Bob.""")
Dear Alice,
Eve's cat has been arrested for catnapping
Sincerely,
Bob.
In [6]:
spam = """Dear Alice,
Eve's cat has been arrested for catnapping
Sincerely,
Bob."""

spam
Out[6]:
"Dear Alice,\nEve's cat has been arrested for catnapping\nSincerely,\nBob."

Similarities Between Strings and Lists

Indexes, slices, and the in and not in operators all work with strings

In [7]:
spam = 'Hello world!'
spam[0]
Out[7]:
'H'
In [8]:
spam[1:5]
Out[8]:
'ello'
In [9]:
spam[-1]
Out[9]:
'!'
In [10]:
'Hello' in spam
Out[10]:
True
In [11]:
'HELLO' in spam
Out[11]:
False
In [12]:
'x' in spam
Out[12]:
False

String Methods

Since strings are immutable, string methods return a new string value rather than modifying string in place

upper(), lower(), title() String Methods

Recall strings are immutable

In [13]:
spam = 'Hello World'
spam.upper()
spam
Out[13]:
'Hello World'

The upper() method returns an uppercase

In [14]:
spam = spam.upper()
spam
Out[14]:
'HELLO WORLD'

The lower() method returns s lowercase string

In [15]:
spam.lower()
Out[15]:
'hello world'

The title() method returns a title case string.

In [16]:
'hello world'.title()
Out[16]:
'Hello World'

isupper() and islower() String Methods

The isupper(), islower() methods return boolean value (True or False) if the string is that respective kind of string

In [17]:
spam = 'Hello World'
spam.islower()
Out[17]:
False
In [18]:
spam = 'HELLO WORLD'
spam.isupper()
Out[18]:
True
In [19]:
spam = ''
spam.isupper()
Out[19]:
False
In [20]:
spam.islower()
Out[20]:
False

isalpha(), isalum(), isdecimal(), isspace(), istitle() String Methods

The isalpha(), isalum(), isdecimal(), isspace(), istitle() methods return boolean value (True or False) if the string is that respective kind of string

Method Desc
isalpha() letters only
isalnum() letters and numbers only
isdecimal() numbers only
isspace() whitespace only
istitle() titlecase only
In [21]:
'hello'.isalpha()
Out[21]:
True
In [22]:
'hello123'.isalpha()
Out[22]:
False
In [23]:
'hello123'.isalnum()
Out[23]:
True
In [24]:
'132'.isdecimal()
Out[24]:
True
In [25]:
'     '.isspace()
Out[25]:
True
In [26]:
'Hello World'.isspace()
Out[26]:
False
In [27]:
'Hello World'[5].isspace()
Out[27]:
True
In [28]:
'This Is Title Case'.istitle()
Out[28]:
True

startswith(), endswith() String Methods

The startswith(), endswith() methods return boolean values

In [29]:
'Hello world'.startswith('H')
Out[29]:
True
In [30]:
'Hello world'.startswith('el')
Out[30]:
False
In [31]:
'Hello world'.endswith('world')
Out[31]:
True
In [32]:
'Hello world'.endswith('a')
Out[32]:
False

join() String Method

The join method returns a string that combines the strings in a list

In [33]:
','.join(['cats', 'rats', 'bats'])
Out[33]:
'cats,rats,bats'
In [34]:
' '.join(['cats', 'rats', 'bats'])
Out[34]:
'cats rats bats'
In [35]:
'\n\n'.join(['cats', 'rats', 'bats'])
Out[35]:
'cats\n\nrats\n\nbats'
In [36]:
print('\n\n'.join(['cats', 'rats', 'bats']))
cats

rats

bats

split() String Method

The split() method returns a list of strings, split from the string it's called on

In [37]:
'My name is Simon'.split()
Out[37]:
['My', 'name', 'is', 'Simon']
In [38]:
'My name is Simon'.split('m')
Out[38]:
['My na', 'e is Si', 'on']

ljust(), rjust(), center() String Methods

The ljust(), rjust(), center() methods return a string padded with spaces

In [39]:
'Hello'.rjust(10)
Out[39]:
'     Hello'
In [40]:
len('     Hello')
Out[40]:
10
In [41]:
'Hello'.ljust(10) # 'Hello     '
Out[41]:
'Hello     '
In [42]:
'Hello'.rjust(10, '*')
Out[42]:
'*****Hello'
In [43]:
'Hello'.center(10)
Out[43]:
'  Hello   '
In [44]:
'Hello'.center(10, '=')
Out[44]:
'==Hello==='

strip(), rstrip(), lstrip() String Methods

The strip(), rstrip(), lstrip() methods return a string with whitespace stripped off the sides

In [45]:
spam = 'Hello'.rjust(10)
spam
Out[45]:
'     Hello'
In [46]:
spam.strip()
Out[46]:
'Hello'
In [47]:
'    x    '.strip()
Out[47]:
'x'
In [48]:
'    x    '.rstrip()
Out[48]:
'    x'
In [49]:
'    x    '.lstrip()
Out[49]:
'x    '
In [50]:
'SpamSpamBaconSpamEggs'.strip('ampS')
Out[50]:
'BaconSpamEggs'

replace() String Method

The replace() method will replace all occurrences of the first string argument with the second string argument

In [51]:
'Hello there'.replace('e', 'XYZ')
Out[51]:
'HXYZllo thXYZrXYZ'

Chaining Methods

In [52]:
'Hello'.upper().isupper()
Out[52]:
True

The pyperclip Module

The pyperclip module has copy() and paste() functions for using the clipboard

Check if pyperclip is installed

In [53]:
import pyperclip

pyperclip.copy(), pyperclip.paste() Functions

In [54]:
import pyperclip
pyperclip.copy('Hello') # to clipboard
pyperclip.paste()
Out[54]:
'Hello'

String Formatting

Using Conversion Specifiers %s

In [55]:
name = 'Alice'
place = 'Main Street'
time = '6 pm'
food = 'turnips'

print("""Hello %s, you are invite to s party at %s
at %s. Please bring %s.""" %(name, place, time, food))
Hello Alice, you are invite to s party at Main Street
at 6 pm. Please bring turnips.

Using .format() with {}

In [56]:
name = 'Sam'
print('hello {}'.format(name))
hello Sam
In [57]:
name = 'John'
age = 12
print('Hi my name is {y} and my age is {x}'.format(x=age, y=name))
Hi my name is John and my age is 12