string - a sequence of characters, indicated with surrounding quotation marks—either single or double, as long as both starting and ending quotation marks are the same. They are not numbers.
'' = null string
len('hello world')
11
len('')
0
hi = 'hello world'
len(hi)
11
print(hi)
hello world
len("hello world")
11
heyno = "Hello, but can't come" #with double quotes we can have a single quote inside a string
print(heyno)
Hello, but can't come
'hello, can't do it' #cannot have single quote inside a string this way
File "/tmp/ipykernel_9389/3416001661.py", line 1 'hello, can't do it' #cannot have single quote inside a string this way ^ SyntaxError: invalid syntax
len(2112) #“integers don’t have a length in Python”
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_9389/1965248679.py in <module> ----> 1 len(2112) #“integers don’t have a length in Python” TypeError: object of type 'int' has no len()
len('1312')
4
index - the character's index is its position in the string;
Character number zero is the character that is zero away from the beginning of the string - the first one
'hello'[0]
'h'
'hello'[1]
'e'
'hello'[2]
'l'
'hello'[3]
'l'
'hello'[4]
'o'
'hello'[5]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) /tmp/ipykernel_9389/2204331286.py in <module> ----> 1 'hello'[5] IndexError: string index out of range
'hello world'[0:3]
'hel'
'2112'[0:3]
'211'
''[0:3]
''
'hello'[0:1]
'h'
'hello'[0]
'h'
''[0:1]
''
''[0]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) /tmp/ipykernel_9389/1334571462.py in <module> ----> 1 ''[0] IndexError: string index out of range
'hello'[0:500]
'hello'
'hello'[450:500]
''
hey = 'hello world'
hey[:3]
'hel'
hey[1:]
'ello world'
ell = hey[1:4]
ell
'ell'
greeting = 'hello world'
greeting[0].upper() + greeting[1:]
'Hello world'
'abcdefgh'[0:9:2]
'aceg'
'hello world'[0:10:2]
'hlowr'
'hello world'[0:11:3]
'hlwl'
'hello world'[0:]
'hello world'
'abcdefgh'[::2]
'aceg'
'0123456789'[::2] #even numbers
'02468'
'0123456789'[::4]
'048'
hey[-1]
'd'
hey[-1:] #the last character
'd'
hey[-5] # the 5th characters backwards
'w'
hey[-5:] # the last 5 characters in the string
'world'
wyatt = 'They flee from me that sometime did me seek / With naked foot, stalking in my chamber.'
'HELLO World'.lower()
'hello world'
original = 'Burma Shave'
lowercase = original.lower()
lowercase
'burma shave'
original
'Burma Shave'
wyatt = wyatt.lower() #overwriting the original string with lower cases
wyatt
'they flee from me that sometime did me seek / with naked foot, stalking in my chamber.'
iterating through wyatt and simply find all the occurrences of a double 'e':
#1. iterate through the string:
for c in wyatt:
print(c)
t h e y f l e e f r o m m e t h a t s o m e t i m e d i d m e s e e k / w i t h n a k e d f o o t , s t a l k i n g i n m y c h a m b e r .
for i in range(len(wyatt)):
print(wyatt[i])
t h e y f l e e f r o m m e t h a t s o m e t i m e d i d m e s e e k / w i t h n a k e d f o o t , s t a l k i n g i n m y c h a m b e r .
for i in range(len(wyatt)):
print(i, wyatt[i]) #adding the index position before each index - [i]
0 t 1 h 2 e 3 y 4 5 f 6 l 7 e 8 e 9 10 f 11 r 12 o 13 m 14 15 m 16 e 17 18 t 19 h 20 a 21 t 22 23 s 24 o 25 m 26 e 27 t 28 i 29 m 30 e 31 32 d 33 i 34 d 35 36 m 37 e 38 39 s 40 e 41 e 42 k 43 44 / 45 46 w 47 i 48 t 49 h 50 51 n 52 a 53 k 54 e 55 d 56 57 f 58 o 59 o 60 t 61 , 62 63 s 64 t 65 a 66 l 67 k 68 i 69 n 70 g 71 72 i 73 n 74 75 m 76 y 77 78 c 79 h 80 a 81 m 82 b 83 e 84 r 85 .
i
85
list(range(len(wyatt)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85]
len(wyatt)
86
wyatt[i]
'.'
for i in range(len(wyatt)):
print (wyatt[i:i+2])
#identifying each pair of letters
th he ey y f fl le ee e f fr ro om m m me e t th ha at t s so om me et ti im me e d di id d m me e s se ee ek k / / w wi it th h n na ak ke ed d f fo oo ot t, , s st ta al lk ki in ng g i in n m my y c ch ha am mb be er r. .
pairs = 0
for i in range(len(wyatt)):
if wyatt[i:i+2] == 'ee':
pairs = pairs + 1
pairs
2
pairs = 0
for i in range(len(wyatt)):
if wyatt[i] == wyatt[i+1]:
pairs = pairs + 1
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) /tmp/ipykernel_9389/3701685584.py in <module> 1 pairs = 0 2 for i in range(len(wyatt)): ----> 3 if wyatt[i] == wyatt[i+1]: 4 pairs = pairs + 1 IndexError: string index out of range
pairs
3
wyatt[86]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) /tmp/ipykernel_9389/3230828111.py in <module> ----> 1 wyatt[86] IndexError: string index out of range
pairs = 0
for i in range(len(wyatt)-1):
if wyatt[i] == wyatt[i+1]:
pairs = pairs + 1
pairs
3
print(pairs)
3
Exe. 8-1
def twin(text):
text = text.lower()
pairs = 0
for i in range(len(text) - 1):
if text[i] == text[i + 1]:
pairs = pairs + 1
return(pairs)
twin(wyatt)
3
twin('Hello world')
1
twin('Alex')
0
text = 'All human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.'
text
'All human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.'
len(text)
170
split(), divides a string into a list of strings, breaking it apart whenever the specified string (the one given as an argument) is found
text.split(' ')
['All', 'human', 'beings', 'are', 'born', 'free', 'and', 'equal', 'in', 'dignity', 'and', 'rights.', 'They', 'are', 'endowed', 'with', 'reason', 'and', 'conscience', 'and', 'should', 'act', 'towards', 'one', 'another', 'in', 'a', 'spirit', 'of', 'brotherhood.']
text
'All human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.'
len(text.split(' ')) #checking len of the split text
30
text.split('and')
['All human beings are born free ', ' equal in dignity ', ' rights. They are endowed with reason ', ' conscience ', ' should act towards one another in a spirit of brotherhood.']
text.split('in') #uses the argument for splitting
['All human be', 'gs are born free and equal ', ' dignity and rights. They are endowed with reason and conscience and should act towards one another ', ' a spirit of brotherhood.']
hi = 'hello world'
hi.split(' ')
['hello', '', '', 'world']
'hello world'.split(' ')
['hello', '', '', 'world']
text.split() # uses any sequence of whitespace
['All', 'human', 'beings', 'are', 'born', 'free', 'and', 'equal', 'in', 'dignity', 'and', 'rights.', 'They', 'are', 'endowed', 'with', 'reason', 'and', 'conscience', 'and', 'should', 'act', 'towards', 'one', 'another', 'in', 'a', 'spirit', 'of', 'brotherhood.']
hi.split()
['hello', 'world']
names = ['Bob', 'Carol', 'Ted', 'Alice']
' & '.join(names)
'Bob & Carol & Ted & Alice'
join - a method of the string that is used to do the joining; it is not a method of the list
names.join(' & ') #a list doesn't have a join attribute
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /tmp/ipykernel_9389/3595420381.py in <module> ----> 1 names.join(' & ') #a list doesn't have a join attribute AttributeError: 'list' object has no attribute 'join'
names
['Bob', 'Carol', 'Ted', 'Alice']
' & '.join(names)
'Bob & Carol & Ted & Alice'
' and/or '.join(names)
'Bob and/or Carol and/or Ted and/or Alice'
'\n'.join(names)
'Bob\nCarol\nTed\nAlice'
print('\n'.join(names)) #printing list as a string in a column with new line
Bob Carol Ted Alice
print(' exists.\n'.join(names)) # element "exists" is just before the new line
Bob exists. Carol exists. Ted exists. Alice
print((' has left.\n'.join(names)) + ' is here.')
Bob has left. Carol has left. Ted has left. Alice is here.
for person in names:
print(person + ' exists.') # iterating in each element in the list "names"
Bob exists. Carol exists. Ted exists. Alice exists.
def naming(string):
for person in ('\n'.join(names)):
if person[-1] == 'l':
return (person + ' exists.')
else:
return (person + ' has left.')
naming(names)
'B has left.'
names
['Bob', 'Carol', 'Ted', 'Alice']
sorted(names) #alphabetically sorted sequence
['Alice', 'Bob', 'Carol', 'Ted']
names
['Bob', 'Carol', 'Ted', 'Alice']
namesorder = names.sort()
namesorder
names.sort()
names
['Alice', 'Bob', 'Carol', 'Ted']
[Exercise 8-2] Same Last Character
Write same_last(), a function that accepts two strings as arguments and returns True if they have the same last letter, False otherwise.
def same_last(name1, name2):
if name1[-1] == name2[-1]:
return True
else:
return False
same_last('Maria', 'Gloria')
True
[Exercise 8-3] Counting Spaces
Write count_spaces(), a function that accepts a string as an argument and returns the number of spaces in the string. Use iteration to determine this.
def count_spaces(text):
count = 0
for i in range(len(text) - 1):
if text[i] == ' ':
count = count + 1
return(count)
count_spaces(names)
0
new = ('Welcome in the new metaverse')
count_spaces(new)
4
[Exercise 8-4] Counting Nonspaces
Write count_nonspaces(), a function that returns the number of characters in a string that are not spaces.
def count_nonspaces(text):
count = 0
for i in range(len(text) - 1):
if text[i] == ' ':
count = count
else:
count = count + 1
return(count)
count_nonspaces(new)
23
len(new)
28
28-4
24