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
Q

Check if a string contains only characters of the alphabet

A

isalpha() returns True if all chars are letters

‘One1’.isalpha() # False
‘One’.isalpha() # True

26
Q

Replace all instances of a substring in a string

A

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’

27
Q

Return the minumum char in a strring

A

Capitalized chars and chars earlier in the alphabet have lower idxs min() will return the char with the lowest index

min(‘strings’) # ‘g’

28
Q

Check if all characters in a string are alphanumeric

A

Alphanumeric values include letters and integers

‘Ten10’.isalnum() # True
‘Ten10.’.isalnum() # False punctuation is not alphanumeric

29
Q

Remove whitespace from left to right or both sides of a string

A

string = ‘ string or whitespaces ‘

string.lstrip() # ‘string or whitespaces ‘

string.rstrip() # ‘ string or whitespaces’

string.strip() # ‘string or whitespaces’

30
Q

Check if a string begins with or ends with a specific char

A

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
Q

Encode a given string as ASCII

A
text = ['Python', 'is', 'a', 'fun', 'programming', 'language'] " ".join(text)
# 'Python is a fun programming language'
32
Q

Check if all chars are whitespace char

A

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

33
Q

What is the effect of multiplying a str by 3?

A

‘penis ‘ * 3 # ‘penis penis penis’

34
Q

Capitalize the first char of each word in a string

A

‘once upon a time’.title() # ‘Once Upon A Time’

35
Q

Concat two strings

A

‘string one’ + ‘ ‘ + ‘string two’ # ‘string one string two’

36
Q

Give an example of using the partition() func

A

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

37
Q

What does it mean for strings to be immutable in Python?

A

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

38
Q

Does defining a string twice create one or more objects in memory?

A

No it only creates a single memory space

animal = ‘dog’
print(id(animal)) #2356782265008

pet = ‘dog’
print(id(pet)) #2356782265008

39
Q

Give an example of using maketrans() and translate()

A
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
Q

Remove vowels from a string

A

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
Q

When would you use rfind()?

A

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