Strings
Strings
Strings
• A string is a sequence of letters (called
characters).
• In Python, strings start and end with single
or double quotes.
>>> “foo”
‘foo’
>>> ‘foo’
‘foo’
Defining strings
• Each string is stored in the computer’s
memory as a list of characters.
>>> myString = “GATTACA”
myString
Accessing single characters
• You can access individual characters by using indices in square brackets.
>>> s = "GATTACA"
>>> s[3] = "C"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> s = s[:3] + "C" + s[4:]
>>> s
'GATCACA'
>>> s = s.replace("G","U")
>>> s
'UATCACA'
Strings are immutable
• String methods do not modify the string;
they return a new string.
>>> sequence = “ACGT”
>>> sequence.replace(“A”, “G”)
‘GCGT’
>>> print sequence
ACGT
Methods:
S.upper()
S.lower()
S.count(substring)
S.replace(old,new)
S.find(substring)
S.startswith(substring), S. endswith(substring)
Printing:
print var1,var2,var3 # print multiple variables
print "text",var1,"text" # print a combination of explicit text (strings) and variables