session_9_string_processing
session_9_string_processing
• String manipulation
• Exercise and Solution (demo)
1
String
• A string is a sequence of letters (called characters).
myString
2
Accessing single characters
• You can access individual characters by using indices in square
brackets.
>>> myString = “GATTACA”
>>> myString[0]
‘G’
>>> myString[1]
‘A’
>>> myString[-1]
‘A’ Negative indices start at the end
>>> myString[-2]
of the string and move left.
‘C’
>>> myString[7]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
3
Substrings
• A substring is the part of a string. Python string provides various
methods to create a substring, check if it contains a substring, index of
substring etc.
>>> myString = “GATTACA”
>>> myString[1:3]
‘AT’
>>> myString[:3]
‘GAT’
>>> myString[4:]
‘ACA’
>>> myString[3:5]
‘TA’
>>> myString[:]
‘GATTACA’
4
More string functionality
5
String methods
>>> dna.count("T") ➔2
>>> dna.lower() ➔ 'gattaca'
>>> dna.upper() ➔ 'GATTACA'
>>> dna.replace("G", "U") ➔'UATTACA‘
>>> dna.replace("C", "U") ➔'GATTAUA'
>>> dna.replace("AT", "**") ➔'G**TACA'
>>> dna.startswith("G") ➔True
>>> dna.startswith("g") ➔False
6
If you have any questions, write it on
a comment section of this video