Strings

 

Take a look at the following:

 
>>> a = “today”

a is the variable. You can think of a as a pointer to the String object - “today” in memory.

 

Immutability

 

Try the following example:

 
>>> a = “this is a sentence.
>>> a.capitalize()
>>> print a

This result is due to the fact that Strings are immutable. This means that we are unable to make changes to a String. What happens here is as follows.

 

A is pointing at the object “this is a sentence.”. When we execute the method capitalize() on the object, a new object “THIS IS A SENTENCE.” is created for us (because we are unable to make in place changes to Strings). However, as a is still pointing at the old object when we run the print command we observe no change. To rectify this, we need to a to point at the newly created String object. We do this as follows.

 
>>> a = “this is a sentence.
>>> a = a.capitalize() #here we tell a to point at the new object
>>> print a

Don't get confused here. In the following example, you have created two String objects and you are just moving the pointer a from one to the other. You are not changing the first String object.

 
>>> a = “this is a sentence.
>>> a = “this is a new sentence”
>>> print a

To prove this, attempt the following:

>>> a = “this is a sentence.
>>> a[0] = 'e' #try change the first character to 'e'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

The example above illustrates that we can not make a change to a String object.

 

String literals and quoting

String literals can be quoted in a few different ways.

 
>>> a = 'hello_world' #single quotes
>>> a = “hello_world” #double quotes
>>> a = '''hello_world''' #triple quoting

Note: the the triple quoting is used to create multi-line strings in Python. Use single or double quoting for single line strings.

 

Review question:

1) How do you think we could create a String from this piece of text? "I am going to London" the man told the lady.

 

Escape characters

An escape character is a character which invokes an alternative interpretation on subsequent characters in a character sequence. Examples are “\n” for a new line and “\t” for a tab space. Use 'r' to suppress escapes as follows:

 
>>> file_path = r'C:\myfolder\file1.txt'
>>> file_path
'C:\\myfolder\\file1.txt'

 

Basic operations on Strings

Concatenation is the joining of two strings. We can do the following:

 
>>> a = “hello  + “world”
>>> a
“hello world”

 

You can't join a string and a number in Python

 
>>> a = “number  + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

 

However, we can first invoke a builtin function to convert the number to string first and then do the concatenation as follows:

 
>>> a = “number  + str(1)
>>> a
'number1'

 

To get the length of a string: use the built-in function len()

 
>>> s = “sunday”
>>> len(s)
6

To ascertain if a string contains a characters: use in

 
>>> 's' in 'sunday'
True

 

Executing methods on String objects

 

 
# s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
>>> str = “zazen academy of technology”
>>> str = str.upper() #remember strings are immutable so do a reassignment
>>> str
 'ZAZEN ACADEMY OF TECHNOLOGY'
 
# s.strip() -- returns a string with whitespace removed from the start and end
>>> str =  This is a sentence 
>>> str = str.strip()
>>> str
 'This is a sentence'
 
# s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are # in the various character classes
>>> str =  1This is a sentence”
>>> result = str.isalpha()
>>> result
 False
 
# s.startswith('other'), s.endswith('other') -- tests if the string starts or # ends with the given other string
>>> str = “This is a sentence”
>>> result = str.startswith(“This”)
>>> result
 True

 

 

 
# s.find('other') -- searches for the given other string (not a regular # expression) within s, and returns the first index where it begins or -1 if not # found
>>> str = “This is a sentence”
>>> result = str.find(“is”)
>>> result
 2
 
# s.replace('old', 'new') -- returns a string where all occurrences of 'old' # have been replaced by 'new'
>>> str = “This is a sentence”
>>> result = str.replace(“i”, “a”)
>>> result
 'Thas as a sentence'

 

 

 
#s.split('delim') -- returns a list of substrings separated by the given delimiter.
>>> str = “This is a sentence”
>>> result = str.split( )
>>> result
 ['This', 'is', 'a', 'sentence']
 
# s.join(list) -- opposite of split(), 
# joins the elements in the given list together using the string as the delimiter.'''
>>> myList = [“a”, “b”, “c”]
>>> result = ','.join(myList)
>>> result
 'a,b,c'

 

 

String formatting

'There is %d %s in the fridge!' % (1, 'beer') = >There is 1 beer in the fridge!