Python Software Developer Interview Questions: Strings

This is a continuation of the tutorial series for Python programming. Previously I wrote an article on Python lists. This article is written in a question-and-answer format. “How to..”, and “What is..” themed questions that often appear on the internet. Hence, I’ll answer a few questions introducing several string methods.
1. What are Python Strings?
Strings or Text are basic components of any data structure. In Python, strings are any values that are enclosed in single(”) or double quotes(“”).
# Assigning strings to variables
current_country = "Finland"
native_country = 'Nepal"print(type(current_country))#Multi-line commentspersonal_info = """ I am Nibesh Khadka. I am from Nepal.Currently I live in Finland. I have degree in IT engineering. I am Machine Learning Engineer, Data Scientist, blogger, python developer, Web Developer and many more. Thanks for reading. """print(type(personal_info))
Output:
<class 'str'>
<class 'str'>
2. How can we use multi-line strings without triple quotes?
Use can use a new line escape character ( “\n” ) to change lines and make a multi-line string.
# Using escape character.using_esc_char = "This is first line.\nThis is second line."
print(using_esc_char)
Output:
This is first line.
This is second line.
3. What is index position? How is it different from counting?
The index is the position of the character in a string. When we count, we usually start from 1. However, the index position starts from 0. Strings can be accessed as string[index_position]. To clarify, let’s try index by normal count.
# Accessing Strings
weather_report="Today's weather is really windy and chilly. I hate it."
#print the length of strings.
print("Length of string is",len(weather_report))
# Lets get last character.
# First lets use length which is 54
print(weather_report[54])
Output:
Length of string is 54.
Traceback (most recent call last): File "python_strings.py", line 42, in <module> print(weather_report[54]) IndexError: string index out of range
Index Error out of range last line indicates that index does not exist that’s because indexing starts from 0, not 1. Hence, the last character index position is:
# Correct way.
print(weather_report[53]) # Or using length directly in index print(weather_report[len(weather_report)-1])
Output:
.
.
4. How do I slice strings in Python?
Slicing strings is also a similar step as a list. To slice a string you have to know the length, and index info. The basic syntax for slicing is: string_name[start:stop:step]
## Slicing Strings
covid = "Covid-19 pandemic was a biggest tragedy of 2020."# Slice to get only Covid-19
print(covid[:8])# Get last 5 characters using -index
print("Last five characters are: ",covid[-5:])# Get frist 10 characters.
print("Last five characters are: ",covid[:5])# Get character 10th to 20th characters.
print("Characters from index 10th to 20th are: ",covid[10:20])
Output:
Last five characters are: 2020.
Last five characters are: Covid
Characters from index 10th to 20th are: andemic wa
Remember: White space is counted if it is inside of the string
5. How can you print each character from a string?
Use for loop to loop through strings and print characters.
# For loop and strings.
which_year="This is 2021."# for loop
for char in which_year:print(char)
Output:
T
h
i
s
i
s
2
0
2
1
.
6. How to print words as whole in a sentence instead of each character
String method split()
can be used to split the strings and convert them to a list, then use a for loop to print each word.
# For loop and split .
which_year="This is 2021."
which_year_list = which_year.split(" ")# for loop
for word in which_year_list:
print(word)
Output:
This
is
2021.
7. How to convert a single word to a list of characters
If a single word is passed into a list() method it can convert a string to a list of characters.
# Word to list
vowel_str = "aeiou"# Print vowel str
print("Vowel letters: ",vowel_str)# Conversion
vowel_lst = list(vowel_str)# Print vowel list
print("Vowel letters in a list: ",vowel_lst)
Output:
Vowel letters: aeiou
Vowel letters in a list: ['a', 'e', 'i', 'o', 'u']
8. How to find the length of a string
Python’s built-in function len() can be used to find the length of strings.
# Find the length of string.
weather_report = "Today's weather is windy in Helsinki."
# print length len()
print("Using len() method: ", len(weather_report))
Output
Using len() method: 37
9. How to check if a certain word/character is in the string
Python has a keyword “in” that can check whether the string’s in another string or not. It returns True or False depending on the result. Similarly, “not” together with “in” can be used to check if the search term is not in the string.
# On sentence
sample_1 = "I am a sentence."#Or in word
sample_2 = "Hi!"# Using in
print("Is a is string sample_1?: {}".format("a" in sample_1))#Using not in
print("! is not in sample_2?: {}".format("!" not in sample_2))
Output:
Is a is string sample_1?: True
! is not in sample_2?: False
10. How to use “if” statement with “in” in strings
A little tweak in the above codes can open more paths using the if statement.
# Using If with in and not in
sentence_sample = "I am going to the UK."
print(sentence_sample)if "am" in sentence_sample:
print("Given sentence is a present tense.")
Output:
I am going to the UK.
Given sentence is a present tense.
Similar logic can be used with “not in” but remember the result of “in” and “not in” means the exact opposite.
11. How to capitalize strings in Python or vice-versa
Python string provides a method upper()
and lower()
to convert strings to uppercase and lowercase, respectively.
# Upper case and Lowercase
# To upper
print("usa".upper())# To lower
print("THE oCean".lower())
Output:
USA
the ocean
12. Can I just make initials uppercase in Python?
Python strings have method title()
that converts the initial in each word to capital letters.
# title
title = "python tutorial - strings"
print(title)print("Titles should have initials in uppercase like,:", title.title())
Output:
python tutorial - strings
Titles should have initials in uppercase like,: Python Tutorial - Strings
13. How to remove unwanted punctuation from the strings
String method strip()
can help remove punctuation from strings.
sample_1 = " 'HI !!!!!!!!!!' "
#print the length before stripping
print("Before stripping length of {} is {}.".format(sample_1, len(sample_1)))
# Remove space's from the edges
sample_1_no_space = sample_1.strip(" ")
#print the length afrer stripping
print("Before stripping length of {} is {}.".format(
sample_1, len(sample_1_no_space)))
Output:
Before stripping length of 'HI !!!!!!!!!!' is 20. Before stripping length of 'HI !!!!!!!!!!' is 15.
13.1. I used strip(“\s+”) but it didn’t work as strip(” “). Why?
It’s true that ” ” or \s+ represent space but \s+ is a regex pattern that is not recognized by the strip method. So, don’t use \s+ for strip methods.
13.2. Can the strip method be used in the middle of the string?
No, the strip only handles the beginning and end of a string. For anything else, you can use replace.
# Replace
sample_2 = "Hi, I am a programmer."# Replace , with !.
print("Before: ", sample_2)
print("After: ", sample_2.replace(",", "!"))
Output:
Before: Hi, I am a programmer.
After: Hi! I am a programmer.
14. How can I turn a list into a string?
join()
can be used to turn the list into a string.
# Join
address =["Helsinki", "Uusimaa", "00230"]
strengths = ["humor", 'creative', 'positive', 'problem solver']# Let's join these.
# address with comma and space
address_joined= ", ".join(address)#print address.
print("I live in {}.".format(address_joined))#strengths with comma and space and use title() at same time
strengths_joined= ", ".join(strengths).title()#print
print("My strengths are {}.".format(strengths_joined))
Output:
I live in Helsinki, Uusimaa, 00230.
My strengths are Humor, Creative, Positive, Problem Solver.
15. How can we add strings in Python?
Adding strings, more precisely string concatenation can be done using different methods.
15.1. Using + to add strings
# String Concatenation using plus
str_1 = "I am a programmer."
str_2 = "I am also a blogger."str_concat = str_1+" "+str_2print("Sentence 1: ", str_1)
print("Sentence 2:",str_2)
print("Combined: ", str_concat)
Output:
Sentence 1: I am a programmer. Sentence 2: I am also a blogger. Combined: I am a programmer. I am also a blogger.
15.1.1. What is print (” Sum result: “+ 1), TypeError: can only concatenate str (not “int”) to str?
When we are using print we often combine two values using “,” or “+”. But what we don’t know is “+” is a strict string operation. It can’t add a non-string to a string. Possible solutions would be
# Either this
print(" Sum result: ", 1)#Or
print(" Sum result: "+ str(1))
While using commas, remember that it adds extra space without manual addition by the coder.
15.2. What is format() method? How can I use it?
Format is another string concatenation method. Once understood it's easy and more readable than other methods. Three variations of format:
# String format
# Default mode
# where order matters
age_info = "I am {} years old. I was born in the month of {}".format(27, "August")
print(age_info)
# Assigning local variable or placeholder
# where order does not make difference but variable name does
relation_status = "I've been {relationship_status} for {years} years.".format(years=100, relationship_status="single")
print(relation_status)
## Formatting integers with palceholders
print("{euro:.1f} euro equivalent in dollars is running for {dollar:.1f} now.".format(euro=1, dollar=1.21 ))
Output:
I am 27 years old. I was born in the month of August
I've been single for 100 years.
1.0 euro equivalent in dollars is running for 1.2 now.
16. What is the escape character in Python? Give some examples of use cases.
Backslash “\” is also known as an escape character in many programming languages. It's used to insert supposedly illegal characters in the string. For example:
Error Case:
travel_mode = "I have a car "Hyundai i20"."print(travel_mode)
Output
travel_mode = "I have a car "Hyundai i20"."
^
SyntaxError: invalid syntax
We are using double quotes inside double quotes. But as such what happens is, that the first pair of double quotes ends before the car brand and starts after it.
Two methods to work around.
- Using escape characters right before quotes inside of our main string, no space allowed.
- Using single quotes either outside or inside to avoid confusion.
travel_mode_1 = "I have a car \"Hyundai i20\"."
travel_mode_2 = "I have a car 'Hyundai i20'."print(travel_mode_1)
print(travel_mode_2)
Output:
I have a car "Hyundai i20".
I have a car 'Hyundai i20'.
Escape characters can be used to escape other illegal characters as well.
Conclusion
I hope you found this Q&A-style tutorial useful. Let me know your thoughts in the comments.