Lesson 20:

String Methods

String methods, unlike list methods, return new strings, not changed strings. This is because strings are immutable.

.lower() and .upper() are methods that return lower and upper case versions of those strings respectively.


In [7]:
spam = 'Hello World!'

print(spam)
print(spam.upper())
print(spam.lower())
print(spam) # variable is unmodified


Hello World!
HELLO WORLD!
hello world!
Hello World!

This methods are useful for case insensitive inputs.


In [10]:
answer = input()

if answer == 'yes':
    print('Playing again.')


yes
Playing again.

This fails if we use capitals. Instead, we can make the input insensitive.


In [6]:
answer = input()

if answer.lower() == 'yes':
    print('Playing again.')


YES
Playing again.

.islower() and .isupper() return boolean responses about the case of the string. There must be at least one upper or lower character to function.


In [14]:
print(spam.islower())

print(spam.upper().isupper()) # Double methods; works because spam.upper() is its own string.


False
True

There are other 'checking' methods that can be used:


In [20]:
print('hello'.isalpha()) # letters only
print('hello123'.isalnum()) # alphanumeric only
print('123'.isdecimal()) # numbers only
print('   '.isspace()) # whitespace only
print('Hello world!'[5].isspace()) # This index of this string is whitespace
print('This Is Title Case'.istitle()) # Titlecase only


True
True
True
True
True
True

There are also .startwith() and .endwith() methods:


In [21]:
print('Hello world!'.startswith('Hello')) # True
print('Hello world!'.startswith('H')) # True
print('Hello world!'.startswith('ello')) # False
print('Hello world!'.endswith('world!')) # True
print('Hello world!'.endswith('world')) # False


True
True
False
True
False

The .join() method joins strings/lists.


In [24]:
print(','.join(['cats','rats','bats']))
print(' '.join(['cats','rats','bats']))
print('\n\n'.join(['cats','rats','bats']))


cats,rats,bats
cats rats bats
cats

rats

bats

The .split() method does the opposite:


In [26]:
print('My name is Simon'.split()) # Default is whitespace split
print('My name is Simon'.split('m')) # Split by m


['My', 'name', 'is', 'Simon']
['My na', 'e is Si', 'on']

The .ljust(), .rjust(), and .center() left, right, and center justify.


In [32]:
print('Hello'.rjust(10))
print('Hello'.ljust(10)) 
print('Hello'.ljust(25,'-')) # Other justify parameter

name = 'Al'
print(name.center(20,'='))


     Hello
Hello     
Hello--------------------
=========Al=========

The .strip() method strips whitespace.


In [38]:
spam = '         Hello'

print(spam)
print(spam.strip())
print(spam) # Remember, strings are immutable; they are not changed via methods

print('        x      '.lstrip()) # Can also left strip
print('        x      '.rstrip()) # Or right strip

print('SpamSpamBaconSpamEggsSpamSpam'.strip('Spam')) # Can even strip out string characters


         Hello
Hello
         Hello
x      
        x
BaconSpamEggs

The .replace() string method does this better.


In [39]:
print(spam)
print(spam.replace('e','XYZ')) # replace e with XYZ


         Hello
         HXYZllo

The Pyperclip Module can be used to copy text to and from the keyboard.


In [42]:
import pyperclip 

# Use pip to install packages into the Python3.5/scripts directory

pyperclip.copy('Hello!') # Copies to clipboard
pyperclip.paste() # Pastes whatever is on clipboard


Out[42]:
'Hello!'

Recap

  • .upper() and .lower() return an uppercase or lowercase string.
  • .isupper(), .islower(), .isalpha, .isalnum, .isdecimal, .isspace(), and .istitle() return Boolean True/False statements about the string.
  • .startswith() and .endswith() also return bools.
  • .join() joins strings in a list with the parameter passed to it.
  • .split() splits its string into a list of strings using the paramater.
  • .rjust(), .ljust(), and .center() returns a string padded with parameters.
  • .replace() replaces all occurences of the first argument with the second argument.
  • The pyperclip module has .copy() and .paste() functions for using the clipboard.