DEV Community

Cover image for Python Strings top 35 Interview Questions
Chinnureddy
Chinnureddy

Posted on β€’ Edited on

52 2 1 1 2

Python Strings top 35 Interview Questions

Basic Concepts

Basic string Operation

1. What is a string in Python?
A string in Python is a sequence of characters. It is an immutable data type, meaning once a string is created, it cannot be modified.

2. How do you define a string in Python?
You can define a string in Python using single ('), double ("), or triple (''' or """) quotes. For example:

single_quoted = 'Hello'
double_quoted = "World"
triple_quoted = '''Python'''
Enter fullscreen mode Exit fullscreen mode

3. Explain the difference between single, double, and triple quotes for defining strings.
Single and double quotes are interchangeable, but using triple quotes allows strings to span multiple lines.

4. How can you concatenate two strings in Python?
Strings can be concatenated using the + operator or by simply placing them next to each other. For example:

concatenated_string = "Hello" + " " + "World"
Enter fullscreen mode Exit fullscreen mode

5. What is the difference between str() and repr()?
str() is used for creating output for end-users, while repr() is mainly used for development and debugging, providing a more unambiguous representation.

6. How do you find the length of a string?
The len() function can be used to find the length of a string:

length = len("Python") 
Enter fullscreen mode Exit fullscreen mode

7. Explain the concept of string indexing in Python.
String indexing allows access to individual characters using their position. Indexing starts from 0 for the first character.

8. How can you access individual characters in a string?
Individual characters can be accessed using square brackets with the index:

python
my_string = "Python"
first_char = my_string[0]  # Accessing the first character
Enter fullscreen mode Exit fullscreen mode

9. What is string slicing? Provide an example.
String slicing extracts a portion of a string.
For example:

my_string = "Python"
substring = my_string[1:4]  # Extracts characters from index 1 to 3
Enter fullscreen mode Exit fullscreen mode

10. How do you reverse a string in Python?
You can reverse a string using slicing with a step of -1:

reversed_string = my_string[::-1]
String Methods
Enter fullscreen mode Exit fullscreen mode

11. Explain the upper() and lower() string methods.
upper() converts all characters in a string to uppercase, while lower() converts them to lowercase.

12. What is the purpose of the strip() method?
The strip() method removes leading and trailing whitespaces from a string.

13. How can you check if a string starts or ends with a specific substring?
The startswith() and endswith() methods can be used for this purpose:

my_string.startswith("Hello")
my_string.endswith("World")
Enter fullscreen mode Exit fullscreen mode

14. What does the replace() method do in Python strings?
The *replace() * method replaces occurrences of a specified substring with another substring:

new_string = my_string.replace("old", "new")
Enter fullscreen mode Exit fullscreen mode

15. Describe the usage of the split() method.
The split() method splits a string into a list of substrings based on a specified delimiter:


words = my_string.split(" ")
Formatting and Interpolation
Enter fullscreen mode Exit fullscreen mode

16. What is string interpolation in Python?
String interpolation is the process of evaluating a string containing placeholders to produce a new string with the placeholders replaced.

17. How does the % formatting operator work with strings?
The % operator is used for string formatting. For

example:

formatted_string = "Hello, %s!" % "Python"
Enter fullscreen mode Exit fullscreen mode

18. Explain the use of the format() method for string formatting.
The format() method provides a more flexible and readable way for string formatting:

formatted_string = "Hello, {}!".format("Python")
Enter fullscreen mode Exit fullscreen mode

19. What is f-string formatting? Provide an example.
F-strings are a concise and readable way to embed expressions inside string literals:

name = "Python"
f_string = f"Hello, {name}!"
Enter fullscreen mode Exit fullscreen mode

20. How can you justify a string in Python?
The ljust(), rjust(), and center() methods are used for left, right, and center justification respectively.

Regular Expressions

21. What is a regular expression?
A regular expression (regex) is a powerful tool for pattern matching in strings.

22. How do you use the re module in Python?
The re module provides support for regular expressions in Python.

23. Explain the difference between match() and search() in regular expressions.
match() checks for a match only at the beginning of a string, while search() looks for a match anywhere in the string.

24. What is the purpose of the findall() method in regular expressions?
The findall() method returns all non-overlapping matches as a list.

25. How can you use groups in regular expressions?
Groups in regular expressions are created using parentheses and allow you to extract specific parts of a match.

Palindromes and Anagrams

26. Write a Python function to check if a string is a palindrome.

def is_palindrome(s):
    return s == s[::-1]
Enter fullscreen mode Exit fullscreen mode

27. Explain the concept of anagrams in strings.
Anagrams are words or phrases formed by rearranging the letters of another.

28. Write a function to determine if two strings are anagrams.

def are_anagrams(s1, s2):
    return sorted(s1) == sorted(s2)
Enter fullscreen mode Exit fullscreen mode

29. How would you reverse words in a given string?

reversed_words = ' '.join(word[::-1] for word in my_string.split())
Enter fullscreen mode Exit fullscreen mode

30. Explain the concept of string permutation.
String permutation refers to all possible rearrangements of characters in a string.

Miscellaneous

31. Write a Python function to count the occurrences of a specific character in a string.

def count_occurrences(s, char):
    return s.count(char)
Enter fullscreen mode Exit fullscreen mode

32. Explain the concept of string immutability.
String immutability means that once a string is created, its contents cannot be changed.

  1. How do you convert a string to a list of characters?
char_list = list("Python")
Enter fullscreen mode Exit fullscreen mode

34. Write a Python function to remove duplicate characters from a string.

def remove_duplicates(s):
    return ''.join(sorted(set(s), key=s.index))
Enter fullscreen mode Exit fullscreen mode

35. Explain the use of the maketrans() and translate() functions.
The maketrans() function creates a translation table, and translate() applies it to replace characters.


@blog by chinnanj. >Happy coding!

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup πŸš€

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (1)

Collapse
 
steal profile image
Chinnureddy β€’

Comment out which is your favourite programming language.

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s dayβ€”drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay