6 Manipulating Strings Flashcards
What are escape characters?
They let yo use characters that are otherwise impossible to use in a string, e.g.:
\t Tab
\n Newline (line break)
\ Backslash
How do you indicate a raw string? What does it do?
> > > print(r’That is Carol's cat.’)
That is Carol's cat.
It ignores all excape characters and prints any backslahs used in the string
What areTriple Quotes useful for?
E.g. for multiline strings or multiline comments.
Also you don´t need escape characters like \n for a new line
How do string interpolation/ the modulo operator work?
> > > name = ‘Al’
age = 4000
‘My name is %s. I am %s years old.’ % (name, age)
‘My name is Al. I am 4000 years old.’
In the modulo operator the %s operator inside the string acts as a marker to be replaced by values following the string.
What is a benefit of the modulo operator?
It requires less time & typing
Also, values (e.g. integers) don´t have to be converted to string
What is the f´string
> > > name = ‘Al’
age = 4000
f’My name is {name}. Next year I will be {age + 1}.’
‘My name is Al. Next year I will be 4001.’
It is similar to the modulo operator, just using{} instead of the %s. Also, it is indicated by an f’ at the beginning of a string.
Name 4 useful string mehods
spam. upper()
spam. lower()
spam. isupper()
spam. islower()
What do .isupper() / .islower() do?
They return boolean values:
True
False
The isX() Methods 5x
isalpha() Returns True if the string consists only of letters
isalnum() Returns True if the string consists only of letters and numbers
isdecimal() Returns True if the string consists only of numeric characters
isspace() Returns True if the string consists only of spaces, tabs, and newlines
istitle() Returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters
Further useful methos
startswith()
endswith()
‘Hello, world!’.startswith(‘Hello’)
join() -> ‘, ‘.join([‘cats’, ‘rats’, ‘bats’])
split() -> ‘My name is Simon’.split()
How can you keep asking someone to enter a password until he enters one only consisting of numbers and letters?
while True: print('Please enter your password.') password = input() if password.isalnum(): break print('Password must consist of letters and numbers only')
Name 3x Text-Justify methods. What values go into the bracket?
justify(nrSpaces, ‘fillerCharacter’):
rjust()
ljust()
center()
How can you make this string appear 10 spaces to the right, with the filler spaces being ‘+’?
spam = ‘Hello’
spam.rjust(10, ‘+’)
‘+++++Hello’