Strings
Strings
NOT mutable, change a string variable result in a new string
Need single or double quotes ââ or ââ to enclose, for example: âHello Worldâ or âHello Worldâ, case sensitive
String is a sequence, iterable
s=âabcâ
s[0]=âaâ
s[1]=âbâ
s[2]=âcâ
It is zero based indexing, index starts from zero
String can be iterated through:
for i in âabcâ:
print(i)
Convert to string, use function str()
For example:
n=12345
str(n) becomes â12345â
String is an object, meaning it has methods and attributes that can be invoked
To see all methods, type
help(<string variable>)
In Jupyter notebook, to see list of methods or attributes
Press shift key after enter <string variable>.

Strings are can be in single quote (â) or double quotes (â)
>>> 'spam eggs' # single quotes
'spam eggsâ
>>> 'doesn\'t' # use " to escape the single quote...
"doesnâtâ
>>> "doesn't" # ...or use double quotes instead
"doesnâtâ
>>> '"Yes," they said.'
#Use single quote to include double quote
'"Yes," they said.â
>>> "\"Yes,\" they said." #use back slash to escape quote mark
'"Yes," they said.â
#use + to concatenate 2 strings
>>>âHelloâ+â Worldâ
Hello World
Strings can be indexed (sub-scripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
>>>Word=âHello Worldâ
>>>Word[0]
âHâ
>>>Word[9]
âdâ
>>>Word[-1]
#Slicing
âdâ
>>>Word[-11]
âHâ
>>>Word[0:]
âHello Worldâ
>>>Word[:9]
âHello Worldâ #character at index 9 is not included.
Last updated
Was this helpful?