41 Python String Questions Flashcards
How would you confirm that two strings share the same identity?
The is operator returns True
animals = ['python', 'gopher'] more\_animals = animals
print(animals == more_animals) # True
print(animals is more_animals) # True
even_more_animals = [‘python’, ‘gopher’]
print(animals == even_more_animals) # True
print(animals is even_more_animals) # False
How would you check if each word in a str begins with a capital letter?
The istitle() func checks if each word is capitalized
print(‘The Hilton’.istitle()) # True
print(‘Kelvin waters’.istitle()) # False
Check if a string contains a specific substring
The in operator will return True if a string contains a substring
print(‘plane’ in ‘The worlds fastest plane’) # True
print(‘car’ in ‘The worlds fastest plane’) # False
Find the index of the first occurrence of a substring in a string
There are 2 different func that will return the starting index(), find() and index().
‘The worlds fastest plane’.find(‘plane’) #19
find() returns -1 if the substring is not found
‘The worlds fastest plane’.find(‘car’) # -1
index() will throw a valueError if occurance missing
‘The words fastest plane’.index(‘plane’) # True
‘The words fastest plane’.index(‘car’) # ValueError
Count the total number of chars in a str
len() will return the length of a string
len(‘The first president of the organization’) # 41
Count the number of a specific char in a string
count() will return the number of occurrences of a specific character
‘The first president of the organisation..’.count(‘o’) # 3
Capitalize the first character of a string
use the capitalize() to do this
‘florida dolphins’.capitalize() # Florida dolphins
What is an f-string and how do you use it?
using f-strings is similiar to using format() # F-strings are denoted by an f before the opening quote
name = 'Kelvin' food = 'lobster tails'
f’Hello. My name is {name} and I like {food}!’
Search a specific part of a str in a sunstring
index() can also be provided with optional start and end indices for searching within a larger string
‘the happiest person in the whole wide world.’.index(‘the’, 10, 44) # 23
Interpolate a variable into a string using format()
format() is similar to using an f-string, though less user friendly
difficulty = 'easy' thing = 'exam'
‘That {} was {}!’.format(thing, difficulty) # ‘That exam was easy!’
Check if a string contains only numbers
isnumeric() returns True if all characters are numeric
print(‘80000’.isnumeric()) # True
print(‘8.0000’.isnumeric()) # False punctuation is none numeric
print(‘900is00’.isnumeric()) # False
Split a string on a specific character
split() function will split a str on a given character or characters
‘This is great’.split(‘ ‘) # [‘This’, ‘is’, ‘great’]
‘not–so–great’.split(‘–’) # [‘not’, ‘so’, ‘great’]
Check if a string is composed of all lower case characters
islower() returns True only if all chars in a string are lowercase
‘all lower case’.islower() # True
‘aLL lower Case’.islower() # False
Check if the first character in a string is lowercase
This can be done by calling the previously func on the first index of a string
‘aPPLE’[0].islower() # True
Can an integer be added to a string in Python
No can not concatenate a string to an integer returns a TypeError
Reverse the string ‘hello world’
We can split the string into a list of char, reverse the list, then rejoin into a single string.
’ ‘.join(reversed(‘hello world’))
Join a list of strings into a single strings, delimited by hypens
join() can join chars in a list with a given char inserted between every element
’-‘.join([‘a’, ‘b’, ‘c’]) # ‘a-b-c’
Check is all characters in a string conform to ASCII
print(‘A’.isacii()) # True
Upper or lowercase an entire string
upper() and lower() return str in all upper and lower cases
sentence = ‘The Cat in the Hat’
sentence.upper() # ‘THE CAT IN THE HAT’
sentence.lower() # ‘the cat in the hat’
Uppercase first and last char of a string
strings aren’t mutable in Python so create a new string
animal = ‘fish’
animal[0].upper() + animal[1:-1] + animal[-1].upper() # ‘FisH’
Check if a string is all uppercase
‘Toronto’.isupper() # False
‘TORONTO’.isupper() # True
When would you use splitlines()?
splitlines() splits a string on line breaks
sentence = ‘It was a stormy night\nThe house creeked\nThe wind blew.’ sentence.splitlines() # [‘It was a stormy night’, ‘The house creeked’, ‘The wind blew’]
Give an example of a string slicing
slicing a string takes up to 3 arguments
string[start_index:end_index: step]
string = ‘I like to eat apples’
string[:6] # ‘I like’
string[7:13] # ‘to eat’
string[0:-1:2] # ‘Ilk oetape’
Convert an integer to a string
type cast
str(5) # ‘5’
Check if a string contains only characters of the alphabet
isalpha() returns True if all chars are letters
‘One1’.isalpha() # False
‘One’.isalpha() # True
Replace all instances of a substring in a string
Without importing re, you can use replace()
sentence = ‘ Sally sells sea shells by the sea shore’
sentence.replace(‘sea’, ‘penis’) # ‘Sally sell penis shells by the penis shore’
Return the minumum char in a strring
Capitalized chars and chars earlier in the alphabet have lower idxs min() will return the char with the lowest index
min(‘strings’) # ‘g’
Check if all characters in a string are alphanumeric
Alphanumeric values include letters and integers
‘Ten10’.isalnum() # True
‘Ten10.’.isalnum() # False punctuation is not alphanumeric
Remove whitespace from left to right or both sides of a string
string = ‘ string or whitespaces ‘
string.lstrip() # ‘string or whitespaces ‘
string.rstrip() # ‘ string or whitespaces’
string.strip() # ‘string or whitespaces’
Check if a string begins with or ends with a specific char
startswith() and endswith() check if a str begins and ends with a specific substring
city = ‘New York’
city.startswith(‘New’) # True
city.endswith(‘N’) # False
Encode a given string as ASCII
text = ['Python', 'is', 'a', 'fun', 'programming', 'language'] " ".join(text) # 'Python is a fun programming language'
Check if all chars are whitespace char
isspace() only returns True if a string is completely made of whitespace
print(‘‘.isspace()) # False
print(‘ ‘.isspace()) # True
print(‘ ‘.isspace()) # True
print(‘ the ‘.isspace()) # False
What is the effect of multiplying a str by 3?
‘penis ‘ * 3 # ‘penis penis penis’
Capitalize the first char of each word in a string
‘once upon a time’.title() # ‘Once Upon A Time’
Concat two strings
‘string one’ + ‘ ‘ + ‘string two’ # ‘string one string two’
Give an example of using the partition() func
partition() splits a string on the first instance of a substring. a tuple of the split str is returned without the substring removed
sentence = ‘If you want to be a ninja’
print(sentence.partition(‘ want ‘)) # (‘If you’, ‘ want’, ‘to be a ninja’)
What does it mean for strings to be immutable in Python?
Once a str obj has been created, it can’t be changed. Modifying that str creates a whole new obj in memory
proverb = ‘Rise each dat before the sun’
print(id(proverb)) # 2356818350768
proverb_two = ‘Rise each day before the sun’ + ‘if its a weekday’ print(id(proverb_two)) # 2356818370992
Does defining a string twice create one or more objects in memory?
No it only creates a single memory space
animal = ‘dog’
print(id(animal)) #2356782265008
pet = ‘dog’
print(id(pet)) #2356782265008
Give an example of using maketrans() and translate()
maketrans() creates a mapping from chars to other chars # translate() then applies that mapping to translate a str
mapping = str.maketrans(‘abcs’, ‘123S’)
‘abc are the first three letters’.translate(mapping) # ‘123 1re the firSt three letterS’
Remove vowels from a string
string = ‘Hello World 2’
vowels = (‘a’, ‘e’, ‘i’, ‘o’, ‘u’)
‘‘.join([c for c in string if c not in vowels]) # ‘Hll Wrld 2’
When would you use rfind()?
rfind() is like find() but it starts searching form the right of a str and return the first matching substring
story = ‘The price is right said Bob. The price is right’
story.rfind(‘is’) # 39