9 Strings Chap 5
9 Strings Chap 5
>>> s = "GATTACA"
0 1 2 3 4 5 6
s G A T T A C A
-7 -6 -5 -4 -3 -2 -1
>>> s = "GATTACA"
>>> s[0] 0 1 2 3 4 5 6
'G'
>>> s[1] G A T T A C A
'A'
>>> s[-1] -7 -6 -5 -4 -3 -2 -1
'A'
>>> s[-2]
'C'
>>> s[7]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
>>>
SLICING IN STRING
string [start : stop : step]
By default start = 0
By default stop = Last Index
By default step = 1
start, stop and step may be negative
CREATING STRINGS
Strings start and end with a single or double quote characters (they
must be the same)
"This is a string"
"This is another string"
""
"Strings can be in double quotes"
‘Or in single quotes.’
'There’s no difference.'
‘Okay, there\’s a small one.’
SOME SPECIAL CHARACTERS
Escape Sequence Meaning
\\ Backslash (keep a \)
\' Single quote (keeps the ')
\" Double quote (keeps the ")
\n Newline
\t Tab
Repeat/Repetition
>>> "A" * 10
'AAAAAAAAAA'
Membership
>>> "G" in "GATTACA"
True
>>> "GAT" in "GATTACA"
True
>>> "AGT" in "GATTACA"
False
STRING FUNCTIONS
>>> len(st) >>> st.startswith("HELL")
17 True
>>> st.startswith("HY")
>>> st.title() False
'Hello How Are You’
>>> st.count("O")
>>> st.capitalize() 3
'Hello how are you’
>>> st.find("OW")
>>> st.lower() 7
'hello how are you‘
>>> st.index("O")
>>> st.upper() 4
'HELLO HOW ARE YOU‘ >>> st.index("W")
8
>>> st.endswith("OU")
True >>> st.replace("U","N")
>>> st.endswith("EW") 'HELLO HOW ARE YON'
False >>> st.replace("O","**")
'HELL** H**W ARE Y**U‘
String Functions
isalnum(), isalpha(), isdigit(), islower(), isspace(),
isupper(), istitle()
>>> str1.split()
['India','is','a','Great','Country']
>>> int("38") + 5
43
>>> int("2.71828")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 2.71828
>>> float("2.71828")
2.71828