Strings

Acknowledgement : the contents of this notebook are partially based on the book "Starting Out with Python (3rd Edition)".

Python provides several ways to access the individual characters in a string. Strings also have methods that allow you to perform operations on them.

Accessing the individual characters

In [2]:
# using for loop
name = 'Ekasit'
for ch in name:
    print(ch)
E
k
a
s
i
t
In [3]:
# this program counts the number of times the letter T
# appears in a string

def main():
    # count variable
    count = 0
    
    # get a string from the user
    my_string = input('Enter a sentence : ')
    
    # count the Ts
    for ch in my_string:
        if ch == 'T' or ch == 't':
            count += 1
            
    # print the result
    print('The letter T appears',count,'times.')
    
# call the main function
main()
Enter a sentence : This is the sentence.
The letter T appears 3 times.
In [6]:
# using indexing
my_name = 'Krikamol'
ch = my_name[3]

print(ch)
k
In [7]:
# IndexError exception
city = 'Bangkok'
print(city[7])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-81078100c4db> in <module>()
      1 # IndexError exception
      2 city = 'Bangkok'
----> 3 print(city[7])

IndexError: string index out of range
In [8]:
# the len function
city = 'Bangkok'
size = len(city)
print(size)
7

String concatenation

In [9]:
firstname = 'Krikamol '
lastname = 'Muandet'

fullname = firstname + lastname
print(fullname)
Krikamol Muandet
In [10]:
letters = 'abc'
letters += 'def' # letters = letters + 'def'
print(letters)
abcdef

Strings are immutable

In [11]:
# this program concatenates strings

def main():
    name = 'Krikamol'
    print('The name is',name)
    
    name = name + ' Muandet'
    print('Now the name is',name)

# call the main function
main()
The name is Krikamol
Now the name is Krikamol Muandet
In [12]:
# assign 'Nuttaporn' to friend
friend = 'Nuttaporn'

# can we change the first character to 'J'?
friend[0] = 'J'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-965d4ee3093a> in <module>()
      3 
      4 # can we change the first character to 'J'?
----> 5 friend[0] = 'J'

TypeError: 'str' object does not support item assignment

String slicing (substrings)

You can use slicing expressions to select a range of characters from a string.

string[start : end]

In [13]:
fullname = 'Mark Robert Smith'
middlename = fullname[5:11]
print(middlename)
Robert
In [14]:
print(fullname[:5])
Mark 
In [15]:
print(fullname[5:])
Robert Smith
In [16]:
print(fullname[:])
Mark Robert Smith
In [17]:
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(letters[0:26:2])
ACEGIKMOQSUWY

Testing, searching, and manipulating strings

Python provides operators and methods for testing strings, searching the contents of strings, and getting modified copies of strings.

In [18]:
# in and not in (string1 in string2)
text =  'The second-year students are good students'
if 'second' in text:
    print("The string 'second' was found.")
else:
    print("The string 'second' was not found.")
The string 'second' was found.
In [19]:
text =  'The second-year students are good students'
if 'third' not in text:
    print("The string 'third' was not found.")
else:
    print("The string 'third' was found.")
The string 'third' was not found.

String methods

In [20]:
# string testing methods
# 1) isalnum()
# 2) isalpha()
# 3) isdigit()
# 4) islower()
# 5) isspace()
# 6) isupper()

string1 = '1200a'
if string1.isdigit():
    print('Digits only')
else:
    print('Have some characters')
Have some characters
In [21]:
letters = 'ABC'
print(letters.isupper())
True
In [22]:
letters = '     '
print(letters.isspace())
True
In [23]:
# modification methods
# 1) lower()
# 2) lstrip()
# 3) lstrip(char)
# 4) rstrip()
# 5) rstrip(char)
# 6) strip()
# 7) strip(char)
# 8) upper()
In [24]:
letters = 'WXYZ'
print(letters, letters.lower())
WXYZ wxyz
In [25]:
letters = 'abcd'
print(letters, letters.upper())
abcd ABCD
In [26]:
# searching and replacing
# 1) endswith(substring)
# 2) find(substring)
# 3) replace(old, new)
# 4) startswith(substring)
In [27]:
filename = input('Enter the filename : ')

if filename.endswith('.txt'):
    print('text file.')
elif filename.endswith('.py'):
    print('Python file')
elif filename.endswith('.doc'):
    print('word file')
else:
    print('Unknown file type')
Enter the filename : students.txt
text file.
In [28]:
# the find method
string = 'The second-year students are good students'
position = string.find('second')

if position != -1:
    print("The word 'second' was found at index",position)
else:
    print("The word 'second' was not found.")
The word 'second' was found at index 4
In [29]:
# the replace method
string = 'The second-year students are good students'
new_string = string.replace('good','bad')
print(new_string)
The second-year students are bad students

The repetition operator

string_to_copy * n

In [30]:
my_string = 'A'*5
print(my_string)
AAAAA

Splitting a string

In [31]:
# this program demonstrates the split method

def main():
    # create a string with multiple words
    my_string = 'one two three four five'
    
    # split the string
    word_list = my_string.split()
    
    # print the list of words
    print(word_list)
    
# call the main function
main()
['one', 'two', 'three', 'four', 'five']
In [32]:
# use different deparator in split method

def main():
    # create a string with a date
    date_string = '11/26/2014'
    
    # split the date
    date_list = date_string.split('/')
    
    # display each piece of the date
    print('Month :', date_list[0])
    print('Day :',date_list[1])
    print('Year :', date_list[2])
    
# call the main function
main()
Month : 11
Day : 26
Year : 2014
In [ ]: