Common python string Interview Questions and Doubts
Hi there! Hope you are doing good.
In this article, we will learn Python String and will understand some python string concepts through examples. If you don’t know – what is Python programming language? its usage and benefit then I recommend you to go through all about python programming language guide.
If you are already familiar with the python programming language and you just want to refresh the python string understanding you are at the right place. Moreover, this article will also help you get prepared with python string interview questions.
Without wasting any time let’s dive in.
What is a Python String?
A string is a sequence of characters. A character can be anything, even a symbol, note that the character is not restricted to the English alphabet.
A string is a data type in python. Python string is a sequence of characters or a single charter enclosed in single, double, or triple quotes. Python treats single and double quotes the same way.
In python to create a string you just need to assign a value to a variable.
For Example –
#!/usr/local/bin/python3 #command to run the file: python3 ./python_string_create.py String1 = "I am Jeevan Gupta" print(String1) String2 = "Hello World python programming" print(String2)
Multiline Python Strings
If you want to create a string variable that consists of multi-line string data we can’t use the above method. The multi-line string data needs to be enclosed in the triple quote. The syntax for triple quotes consists of three single or double quotes.
For Example –
#!/usr/local/bin/python3 #command to run the file: python3 ./multi_line_string.py #using 3 single quote MultiLineString1 = ''' Programming isn't about what you know; it's about what you can figure out. The only way to learn a new programming language is by writing programs in it. ''' print(MultiLineString1) #using 3 double quote MultiLineString2 = """ Programming isn't about what you know; it's about what you can figure out. The only way to learn a new programming language is by writing programs in it. """ print("\n",MultiLineString2)
Accessing value in the Python String
Python string data type is actually an array, same as strings datatype in other programming languages. Python supports only string data type and not CHAR (character data type). The character data type is a simple string consisting of one element.
Since the python string is an array, we can access the string data using the method of indexing. Python also supports negative indexing, which is used to access charters from the last of a string.
NOTE: in negative indexing, the index starts from 1 and not 0. What I mean by that is to say the string is “example” and I want to get 3 characters from the end, then I will say string[-3] and not string[-4]. This will be the case in positive indexing.
For example-
#!/usr/local/bin/python3 #command to run the file: python3 ./string_access.py String = "python string is an array" print("\nlength of string : ", len(String)) #gives 3rd character print(String[3]) #gives 2 character from end print(String[-2])
Python String Slicing
This technique is very similar to accessing the string character. Here we need to provide start index and end index positions. String slicing as the name suggests is an operation of accessing some sequence of characters of a string i.e substring of a string.
Note:
- String indexing also starts from 0, since a string is also an array as I mentioned above.
- In string slicing, the end index is not part of a range selection. What I mean by that is to say a string is an “example” and string slicing is [1:3]. This slicing operation will give us “xa”.
For example: string[1:2], String[-5:-1] and String[:1]
As we can see from the above example a string can be sliced in different ways. Let’s see them in detail below.
Slice from start
Slice from start means accessing character from the start of string till the end index specified. The syntax is string[:5]. As you can see we are leaving the start index due to which range will start from the start of the string.
Slice to the end
Slice to the end means accessing the character from the specified index position till the end of the string. The syntax is string[2:]. As you can see we are leaving out the end index due to which range will go till the end of the string.
Python String Negative Indexing
As we have seen in accessing the string section that negative string can be used to access the string character from last. With the same concept, we can use the negative index to slice the string from the end of the string.
Syntax: string[-5:-2], means get the sequence of characters from the python string from the 5th position from the end till the 2nd position from the end.
For example –
#!/usr/local/bin/python3 #command to run the file: python3 ./string_slicing.py String = "string slicing example" print(String[1:3]) print(String[-5:-1]) print(String[:4]) print(String[8:]) print(String[-3:])
Python String Updating
As we know string is an array and we can access string characters through the indexing method. Right?. Using this flexibility we can also update an existing string. To update an existing string we need (re)assign a variable to another string. The new value can be related to its previous value or to a completely different string altogether.
For example –
#!/usr/local/bin/python3 #command to run the file: python3 ./string_update.py String = "string update example" print("original string : ",String) String = String[:-7] + "using indexing" print("\nstring after update : ",String)
Python String Concatenation
Python string concatenation means combining or merging two strings. This can be achieved using the “+” operator. Note that we can’t use the + operator to combine string and number.
For Example –
#!/usr/local/bin/python3 #command to run the file: python3 ./string_concatenation.py String1 = "I am Jeevan Gupta." String2 = "Welcome to Python String Tutorial" String = String1 + String2 print(String)
Python String Formatting
As we learned from the above section python gives an error when trying to combine a string with a number. To achieve this python gives us the format() method with {} placeholders.
The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are.
For example –
#!/usr/local/bin/python3 #command to run the file: python3 ./string_formating.py price = 35 num = 4 String1 = "I bought {} icecream for {} rupee." print(String1.format(num,price))
Python String Built-In Methods
Method | Description |
---|---|
capitalize() | Converts the first character to uppercase |
casefold() | Converts a string into lower case |
center() | Returns a centered string |
count() | Returns the number of times a specified value occurs in a string |
encode() | Returns an encoded version of the string |
endswith() | Returns true if the string ends with the specified value |
expandtabs() | Sets the tab size of the string |
find() | Searches the string for a specified value and returns the position of where it was found |
format() | Formats specified values in a string |
format_map() | Formats specified values in a string |
index() | Searches the string for a specified value and returns the position of where it was found |
isalnum() | Returns True if all characters in the string are alphanumeric |
isalpha() | Returns True if all characters in the string are in the alphabet |
isdecimal() | Returns True if all characters in the string are decimals |
isdigit() | Returns True if all characters in the string are digits |
isidentifier() | Returns True if the string is an identifier |
islower() | Returns True if all characters in the string are lower case |
isnumeric() | Returns True if all characters in the string are numeric |
isprintable() | Returns True if all characters in the string are printable |
isspace() | Returns True if all characters in the string are whitespaces |
istitle() | Returns True if the string follows the rules of a title |
isupper() | Returns True if all characters in the string are upper case |
join() | Joins the elements of an iterable to the end of the string |
ljust() | Returns a left justified version of the string |
lower() | Converts a string into lower case |
lstrip() | Returns a left trim version of the string |
maketrans() | Returns a translation table to be used in translations |
partition() | Returns a tuple where the string is parted into three parts |
replace() | Returns a string where a specified value is replaced with a specified value |
rfind() | Searches the string for a specified value and returns the last position of where it was found |
rindex() | Searches the string for a specified value and returns the last position of where it was found |
rjust() | Returns a right-justified version of the string |
rpartition() | Returns a tuple where the string is parted into three parts |
rsplit() | Splits the string at the specified separator, and returns a list |
rstrip() | Returns a right trim version of the string |
split() | Splits the string at the specified separator, and returns a list |
splitlines() | Splits the string at line breaks and returns a list |
startswith() | Returns true if the string starts with the specified value |
strip() | Returns a trimmed version of the string |
swapcase() | Swaps cases, the lower case becomes the upper case and vice versa |
title() | Converts the first character of each word to uppercase |
translate() | Returns a translated string |
upper() | Converts a string into upper case |
zfill() | Fills the string with a specified number of 0 values at the beginning |
Python String Interview Questions/Exercise
1. Can you find out if two strings have the same value and identity? If Yes then how?
Ans: To answer the above question we need to use the “==” and “is” operators. Note that “==” is used mostly to check value and “is” is used to identify. Identity means the location of the object in memory space.
#The above question is not that direct there are two possibilities #One, if say String1 = ["Odisha", "Kerala"] #and we create another string String2 = String1 #In this case print(String1 == String2) #=> True print(String1 is String2) #=> True #Second, if String3 = ["Odisha", "Kerala"] String4 = ["Odisha", "Kerala"] print(String3 == String4 ) #=> True print(String3 is String4 ) #=> False
2. Is there any inbuilt method to check the identity of two strings?
Ans: Yes, we can use the id() function to return the string object’s memory address.
3. Can you determine if a given string’s each word starts with a capital charter and the number of words a string has?
Ans: By using the inbuilt method istitle()
print( 'Python String Interview'.istitle() ) #=> True print( 'Python string'.istitle() ) #=> False print( 'python string'.istitle() ) #=> False
4. How can you check if a string contains a specific substring and return its index?
Ans: To check the presence of a substring in a string we can use the “in” operator. If a substring is present in the string the operator will return True otherwise False.
#To check the presence of a substring in a string we can use the “in” operator. If a substring is present in the string the operator will return True otherwise False. #say String1 = "Welcome to python string interview questions example by Jeevan Gupta" print("Jeevan" in String1) #=> True print("world" in String1) #=> False #In the same way you can get the index using find() or index() method. print('Welcome to python string interview questions example by Jeevan Gupta'.find('string')) #=> 19 print('Welcome to python string interview questions example by Jeevan Gupta'.find('list')) #=> -1 #OR print('Welcome to python string interview questions example by Jeevan Gupta'.index('string')) #=> 19 print('Welcome to python string interview questions example by Jeevan Gupta'.index('dictionary')) #=> ValueError: substring not found
5. Do you know what an f-string is and how to use it?
Ans: f-string is very similar to format(). F-string helps in string interpolation. F-string was introduced in Python3.6. You can read all about it in PEP 498, which was written by Eric V. Smith in August of 2015.
To use the f-string, we need to prefix the string with the letter “f”. This technique provides a better and more convenient way to embed python expressions inside string literals for formatting.
price = 35 num = 4 name = “Arun” String1 = f"I bought {num} icecream of {price} rupee for {name}" #=> "I bought 4 icecream of 35 rupee for Arun"
6. How to reverse a string?
Ans: There is no direct function to reverse a string in python. but the easiest way is to use slicing with negative indexing.
String1 = "python string" print(String1[::-1]) # there is a function reversed() which will return the reverse version of the string as a reversed object. String2 = ''.join(reversed(String1)) print(String2)
7. How to remove whitespace from both or specific ends of a string?
Ans: we can use strip(), lstrip() and rstrip() methods to remove the whitespace from the desired position of the given string.
string = ' string of whitespace ' print(string.lstrip()) #=> 'string of whitespace ' print(string.rstrip()) #=> ' string of whitespace' print(string.strip()) #=> 'string of whitespace'
8. What happens when you multiply a string with any number?
Ans: the string gets concatenated together by N number of time
Say String1 = “Good”
String2 = String1 * 4 $=> “GoodGoodGoodGood”
9. Is a string mutable or immutable in python? Can you prove it?
Ans: A string is mutable when we modify a python string that string creates a whole new object in memory space i.e. a new memory space id gets associated with the object.
The id can be checked using the id() function.
String1 = 'python string' print(id(String1)) #=> 140414882048752 String1 = 'python string' + 'tutorial' print(id(String1))#=> 140414882299296
10. How can you account for the number of times a word is appearing in a string?
Ans: We can use the count() inbuilt method to find the number of occurrences of a substring in a string.
Strin1 = "python string tutorial with interview question on python string" print(Strin1.count('string'))
Hope I have made it easy to understand the python string and its basic operations. If you Like this article and think it was easy to understand and might help someone you know do share it with them. Thank You! see you soon.
If you have any questions or comments feel free to reach me at.
Checkout out other python concept covered in Python Tutorial