41 Python String Questions Flashcards

1
Q

How would you confirm that two strings share the same identity?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How would you check if each word in a str begins with a capital letter?

A

The istitle() func checks if each word is capitalized

print(‘The Hilton’.istitle()) # True
print(‘Kelvin waters’.istitle()) # False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Check if a string contains a specific substring

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Find the index of the first occurrence of a substring in a string

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Count the total number of chars in a str

A

len() will return the length of a string

len(‘The first president of the organization’) # 41

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Count the number of a specific char in a string

A

count() will return the number of occurrences of a specific character

‘The first president of the organisation..’.count(‘o’) # 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Capitalize the first character of a string

A

use the capitalize() to do this

‘florida dolphins’.capitalize() # Florida dolphins

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is an f-string and how do you use it?

A
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}!’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Search a specific part of a str in a sunstring

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Interpolate a variable into a string using format()

A

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!’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Check if a string contains only numbers

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Split a string on a specific character

A

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’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Check if a string is composed of all lower case characters

A

islower() returns True only if all chars in a string are lowercase

‘all lower case’.islower() # True
‘aLL lower Case’.islower() # False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Check if the first character in a string is lowercase

A

This can be done by calling the previously func on the first index of a string

‘aPPLE’[0].islower() # True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Can an integer be added to a string in Python

A

No can not concatenate a string to an integer returns a TypeError

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Reverse the string ‘hello world’

A

We can split the string into a list of char, reverse the list, then rejoin into a single string.

’ ‘.join(reversed(‘hello world’))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Join a list of strings into a single strings, delimited by hypens

A

join() can join chars in a list with a given char inserted between every element

’-‘.join([‘a’, ‘b’, ‘c’]) # ‘a-b-c’

18
Q

Check is all characters in a string conform to ASCII

A

print(‘A’.isacii()) # True

19
Q

Upper or lowercase an entire string

A

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’

20
Q

Uppercase first and last char of a string

A

strings aren’t mutable in Python so create a new string

animal = ‘fish’
animal[0].upper() + animal[1:-1] + animal[-1].upper() # ‘FisH’

21
Q

Check if a string is all uppercase

A

‘Toronto’.isupper() # False
‘TORONTO’.isupper() # True

22
Q

When would you use splitlines()?

A

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’]

23
Q

Give an example of a string slicing

A

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’

24
Q

Convert an integer to a string

A

type cast

str(5) # ‘5’

25
Check if a string contains only characters of the alphabet
*isalpha()* returns True if all chars are letters ## Footnote 'One1'.isalpha() # False 'One'.isalpha() # True
26
Replace all instances of a substring in a string
Without importing re, you can use *replace()* ## Footnote sentence = ' Sally sells sea shells by the sea shore' sentence.replace('sea', 'penis') # 'Sally sell penis shells by the penis shore'
27
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 ## Footnote min('strings') # 'g'
28
Check if all characters in a string are alphanumeric
Alphanumeric values include letters and integers ## Footnote 'Ten10'.isalnum() # True 'Ten10.'.isalnum() # False punctuation is not alphanumeric
29
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'
30
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
31
Encode a given string as ASCII
``` text = ['Python', 'is', 'a', 'fun', 'programming', 'language'] " ".join(text) # 'Python is a fun programming language' ```
32
Check if all chars are whitespace char
*isspace()* only returns True if a string is completely made of whitespace ## Footnote print(''.isspace()) # False print(' '.isspace()) # True print(' '.isspace()) # True print(' the '.isspace()) # False
33
What is the effect of multiplying a str by 3?
'penis ' \* 3 # 'penis penis penis'
34
Capitalize the first char of each word in a string
'once upon a time'.title() # 'Once Upon A Time'
35
Concat two strings
'string one' + ' ' + 'string two' # 'string one string two'
36
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 ## Footnote sentence = 'If you **want** to be a ninja' print(sentence.partition(' want ')) # ('If you', ' **want**', 'to be a ninja')
37
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 ## Footnote 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
38
Does defining a string twice create one or more objects in memory?
No it only creates a single memory space ## Footnote animal = 'dog' print(id(animal)) #2356782265008 pet = 'dog' print(id(pet)) #2356782265008
39
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'
40
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'
41
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 ## Footnote story = 'The price is right said Bob. The price is right' story.rfind('is') # 39