Show
How to crush algorithm questions by mastering string fundamentalsPhoto by ThisisEngineering RAEng on UnsplashI’ve started tracking the most commonly used functions while doing algorithm questions on LeetCode and HackerRank. Being a good engineer isn’t about memorizing a language’s functions, but that doesn’t mean it’s not helpful. Particularly in interviews. This is my string cheatsheet converted into a list of questions to quiz myself. While these are not interview questions, mastering these will help you solve live coding questions with greater ease. How well do you know Python strings? 1. How would you confirm that 2 strings have the same identity?The Don’t confuse animals = ['python','gopher'] Notice above how Additionally, the name = 'object' 2. How would you check if each word in a string begins with a capital letter?The print( 'The Hilton'.istitle() ) #=> True 3. Check if a string contains a specific substringThe print( 'plane' in 'The worlds fastest plane' ) #=> True 4. Find the index of the first occurrence of a substring in a stringThere are 2 different functions that will return the starting index,
'The worlds fastest plane'.find('plane') #=> 19
'The worlds fastest plane'.index('plane') #=> 19 5. Count the total number of characters in a string
len('The first president of the organization..') #=> 19 6. Count the number of a specific character in a string
'The first president of the organization..'.count('o') #=> 3 7. Capitalize the first character of a stringUse the 'florida dolphins'.capitalize() #=> 'Florida dolphins' 8. What is an f-string and how do you use it?New in python 3.6, f-strings make string
interpolation really easy. Using f-strings is similar to using F-strings are denoted by an name = 'Chris' 9. Search a specific part of a string for a substring
'the happiest person in the whole wide world.'.index('the',10,44) Notice how the above returned 'the happiest person in the whole wide world.'.index('the') 10. Interpolate a variable into a string using format()
difficulty = 'easy' 11. Check if a string contains only numbers
'80000'.isnumeric() #=> True Note that punctuation is not numeric. '1.0'.isnumeric() #=> False 12. Split a string on a specific characterThe 'This is great'.split(' ') 13. Check if a string is composed of all lower case characters
'all lower case'.islower() #=> True 14. Check if the first character in a string is lowercaseThis can be done by calling the previously mentioned function on the first index of the string. 'aPPLE'[0].islower() #=> True 15. Can an integer be added to a string in Python?In some languages this can be done but python will throw a 'Ten' + 10 #=> TypeError 16. Reverse the string “hello world”We can split the string into a list of characters, reverse the list, then rejoin into a single string. ''.join(reversed("hello world")) 17. Join a list of strings into a single string, delimited by hyphensPython’s '-'.join(['a','b','c']) 18. Check if all characters in a string conform to ASCIIThe print( 'Â'.isascii() ) #=> False 19. Uppercase or lowercase an entire string
sentence = 'The Cat in the Hat'sentence.upper() #=> 'THE CAT IN THE HAT' 20. Uppercase first and last character of a stringAs in a past example, we’ll target specific indices of the string. Strings aren’t mutable in Python so we’ll build an entirely new string. animal = 'fish'animal[0].upper() + animal[1:-1] + animal[-1].upper() 21. Check if a string is all uppercaseSimilar to 'Toronto'.isupper() #=> False 22. When would you use splitlines()?
sentence = "It was a stormy night\nThe house creeked\nThe wind blew."sentence.splitlines() 23. Give an example of string slicingSlicing a string takes up to 3 arguments,
string = 'I like to eat apples'string[:6] #=> 'I like' 24. Convert an integer to a stringUse the string constructor, str(5) #=> '5' 25. Check if a string contains only characters of the alphabet
'One1'.isalpha() 26. Replace all instances of a substring in a stringWithout importing the regular expressions module, you can use sentence = 'Sally sells sea shells by the sea shore'sentence.replace('sea', 'mountain') 27. Return the minimum character in a stringCapitalized characters and characters earlier in the alphabet have lower indexes. min('strings') #=> 'g' 28. Check if all characters in a string are alphanumericAlphanumeric values include letters and integers. 'Ten10'.isalnum() #=> True 29. Remove whitespace from the left, right or both sides of a string
string = ' string of whitespace ' 30. Check if a string begins with or ends with a specific character?
city = 'New York'city.startswith('New') #=> True 31. Encode a given string as ASCII
'Fresh Tuna'.encode('ascii') 32. Check if all characters are whitespace characters
''.isspace() #=> False 33. What is the effect of multiplying a string by 3?The string is concatenated together 3 times. 'dog' * 3 34. Capitalize the first character of each word in a string
'once upon a time'.title() 35. Concatenate two stringsThe additional operator can be used to concatenate strings. 'string one' + ' ' + 'string two' 36. Give an example of using the partition() function
sentence = "If you want to be a ninja"print(sentence.partition(' want ')) 37. What does it mean for strings to be immutable in Python?Once a string object has been created, it cannot be changed. “Modifying” that string creates a whole new object in memory. We can prove it by using the proverb = 'Rise each day before the sun' Concatenating 38. Does defining a string twice (associated with 2 different variable names) create one or two objects in memory?For example,
writing It only creates one. I found this unintuitive the first time I came across it. But this helps python save memory when dealing with large strings. We’ll prove this with animal = 'dog' 39. Give an example of using maketrans() and translate()
# create mapping Notice above how we changed the values of every 40. Remove vowels from a stringOne option is to iterate over the characters in a string via list comprehension. If they don’t match a vowel then join them back into a string. string = 'Hello 1 World 2'vowels = ('a','e','i','o','u')''.join([c for c in string if c not in vowels]) 41. When would you use rfind()?
story = 'The price is right said Bob. The price is right.' ConclusionAs I often explained to an old product manager, engineers aren’t dictionaries of stored methods. But sometimes a little less googling can make coding more seamless and enjoyable. I hope you crushed this. If you found it too easy, you may be interested in my other article, 54 Python Interview Questions. What is the return value of the string method Lstrip?Return Value from lstrip()
lstrip() returns a copy of the string with leading characters stripped. All combinations of characters in the chars argument are removed from the left of the string until the first mismatch.
What is Lstrip () function in string?Python String lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed). If no argument is passed, it removes leading spaces.
How strip () method works in Python including Lstrip () and Rstrip?Python Trim String. strip(): returns a new string after removing any leading and trailing whitespaces including tabs ( \t ).. rstrip(): returns a new string with trailing whitespace removed. ... . lstrip(): returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string.. What method returns the list of the words in a string?Method#1: Using split() method
The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.
|