Python String

Working with string in Python

# Strings are created with " or '
"This is a string."
'This is also a string.'
 
"Hello " + "world!"  # => "Hello world!"
 
# A string can be treated like a list of characters
"This is a string"[0]  # => 'T'
 
# Get length of the string
len("This is a string")  # => 16
 
"{} can be {}".format("Strings", "interpolated")  # => "Strings can be interpolated"
 
# You can repeat the formatting arguments to save some typing.
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
 
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna")  # => "Bob wants to eat lasagna"
 
# Python 2.x syntax
message = "You don't have permission to view this page. %s" % error_message
 
# Convert to string (Casting to string)
str(77)

The String Methods

>>> spam = 'Hello world!'
>>> spam = spam.upper()
>>> spam
'HELLO WORLD!'
 
>>> spam = spam.lower()
>>> spam
'hello world!'
 
>>> spam = 'Hello world!'
>>> spam.islower()
False
>>> spam.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'hello'.islower()
True
 
>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
>>> 'hello123'.isalnum()
True
>>> '123'.isdecimal()
True
>>> ' '.isspace()
True
>>> 'This Is Title Case'.istitle()
True
>>> 'This IS not Title Case'.istitle()
False
 
>>> 'Hello world!'.startswith('Hello')
True
>>> 'Hello world!'.endswith('world!')
True
 
>>> ', '.join(['cats', 'dogs', 'parrots'])
'cats, dogs, parrots'
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
>>> 'cats, dogs, parrots'.split(', ')
['cats', 'dogs', 'parrots']
 
>>> spam = '''Line one
Line two
Line three'''
>>> spam.split('\n')
['Line one', 'Line two', 'Line three']
 
>>> spam = ' Hello World '
>>> spam.strip()
'Hello World'
>>> spam.lstrip()
'Hello World '
>>> spam.rstrip()
' Hello World'
 
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS') # strip occurences of a, m, p, and S from the ends of the string
'BaconSpamEggs'

Slicing strings in Python:

>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'

'in' and 'not in' with strings in Python:

>>> 'Hello' in 'Hello World'
True
>>> 'HELLO' in 'Hello World'
False
>>> '' in 'spam'
True
>>> 'cats' not in 'cats and dogs'
False

Leave a Reply

Your email address will not be published. Required fields are marked *