Comprehensive guide covering various interview questions on Python string concepts and manipulation techniques

7. Check if a Python string starts or ends with? Examples?

Python makes it really simple to check whether a string starts or ends with particular words or characters.
You can use:

startswith() :- checks for how the string begins
endswith():- checks for how the string ends.
Both return True or False, meaning yes or no.

Example: startswith()
text = "Python is fun"
print(text.startswith("Python")) # True
print(text.startswith("Java")) # False
This checks if a sentence starts with its first word, which is "Python."

Example: endswith()
file = "photo.jpg"
print(file.endswith(".jpg")) # True
print(file.endswith(".png")) # False
This greatly helps when dealing with filenames and it's checking if the file is .jpg or .png.

Quick Tip:
In case you're unsure about upper and lowercase letters just lower everything:
text = "Hello World"
print(text.lower().startswith("hello")) # True


8. Python find() vs index() for substring difference?

Both functions find() and index() are intended to search for a substring within a string and return the starting location for that substring.
The main difference lies in the handling of the case when the search fails.

find() – Always a Safe Search
If it find the substring it returns the starting position.
If it cannot find the substring it returns -1.
text = "Python is fun"
print(text.find("fun")) # Output: 10
print(text.find("Java")) # Output: -1
So find() is what you should use if you are not very sure about the word being there.

index()
If the text was found, it performs same as find().
In case the text was not found, it throws an exception.
text = "Python is fun"
print(text.index("fun")) # Output: 10
print(text.index("Java")) # ❌ This gives an error!

An easy way to remember this:
Use find() if you want to check safely.
Use index() only if you know for sure the text exists – or are ready to handle an error!


9.Best way to format strings in Python? Understanding f-strings.

F-strings came into popularity with the initiation of Python 3.6. They have gained preference for many because they are simple, neat and easy to read.
What is f-string?
F-string stands for "formatted string literal" which handles the task of injecting variables or values directly into your string with an f in front of your string then placing your variable in between curly braces {}.

Example:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 25 years old.

Forget using all those impertinent commas and symbols - simply write out your statement and insert the variable(s) whenever it pleases you.
You can even do math or simple expressions inside {}:
price = 10
quantity = 3
print(f"Total price: ${price * quantity}")
Output:
Total price: $30

Reason Why f-string is way better compared to earlier systems:
They are the easiest to write and read.
You may alternatively enter variables, numbers and even brief calculations in between the strings.
They are way faster .
The code is neat and small.

The old ways of formatting (mostly to be avoided):
% Way (old and unreadable):
name = "Alice"
print("Hello, %s" % name)
.format() method (still works but longer):
name = "Alice"
print("Hello, {}".format(name))

Conclusion:
If you're formatting strings in Python, use f-strings.
To do so, just put an f before the string and use {} to add whatever you want.


10.Python string replace() how does it work?

In Python, replace() is a method that is used to replace a word or string with another within a given string.
It is very useful when you want to modify or clean some text.
And the great thing about it? It never modifies the original string but returns a modified new string.

Simple example:
text = "I like apples"
new_text = text.replace("apples", "oranges");
print(new_text)

Output:
I like oranges
Here, "apples" got replaced by "oranges" in the new string.

How it Works:
The Syntax of Method Replace () Looks Like This:
string.replace(old_text, new_text)
old_text: the word or part you want to change
new_text: what you want to put in its place
Except for your instruction, it will do the job of replacement everywhere it finds that word.

Example with multiple replacements:
sentence = "hello world, hello again"
print(sentence.replace("hello", "hi"))

Output:
hi world, hi again
So basically from now on every "hello" will be referenced as "hi".

Well, what if you want to replace only a few?
If you want, you can include a number specifying how many times to replace.
text = "one one one"
print(text.replace("one", "two", 2))
Output:
two two one
Only the first two "one"s were changed to "two".

Key takeaways:
replace() is going to take some characters or words from a string and replace them
It is going to give you a new string, the original one remains unchanged
You can specify whether to replace all occurrences or just a few by adding a count


11.Python function to check if string is palindrome?

Palindrome is a word/phrase that is the same no matter whether it is read backward or forwards.
Some common examples include:
"madam"
"racecar"
"nurses run"
If you reverse it, it still looks the same.

How to say if a given string is a palindrome in Python?
You can write a small function to do this:
def is_palindrome(text):
  cleaned = text.lower().replace(" ", "") # Lowercase + remove spaces
  return cleaned == cleaned[::-1]

What this code does:
text.lower() – turn everything lower to make it easier matching
.replace(" ", "") – removes spaces (optional, but helpful for phrases)
cleaned[::-1] - Reverses the string
Then it checks: Is the original (cleaned) string the same as the reversed one?
If yes, it's a palindrome!

An example:
print(is_palindrome("Racecar")) # True
print(is_palindrome("Hello")) # False
print(is_palindrome("nurses run")) # True

In simple words:
This function tests a word or sentence to see if it is a palindrome.
It works even if the letters are uppercased or there is spacing.
It does not change original word it only compares reverse.


12.Python code to count character in a string?

If you want to count the total number of characters in a string using Python programming, sometimes, you want to know how many times a character appears in a word or a sentence and how it counts in Python, By just some lines of code this is very easy.

Here is the simplified function for it:

def count_characters(text): count = {} for char in text: if char in count: count[char] += 1 else: count[char] = 1 return count

Example:
result = count_characters("banana")
print(result)

Output:
{'b': 1, 'a': 3, 'n': 2}
So, in the word "banana":
The letter 'b' appears 1 time
'a' appears 3 times
'n' appears 2 times

How does it work?
The function goes through each character in the text, one by one and through each character in the entire text.
If the character already exists in count, we increment its value.
Or, if this is a new character, we can start counting it from first 1.
And at the end, you have a dictionary that tells you how many times the character occurred.


13.Remove duplicate chars from Python string (keep order)?

We are going to study removing duplicate characters from a string (but keeping the order of the characters). Suppose we have a string and we want to remove all the repeated characters from it while keeping the first ones that appeared in their original order. Implementation in Python is really simple and will just take two or three statements.

Let’s see how simple it is:

def remove_duplicates(text): result = "" seen = set() for char in text: if char not in seen: result += char seen.add(char) return result

Example:
print(remove_duplicates("programming"))
Output: For "programming":
progamin
The first time it saw a letter such as 'p', 'r', 'o', etc., it kept it but on the second time it just ignored it whenever it saw the same letter again (`second 'm' or second 'g'`).

Thus it retains only the first time each letter had shown up.
The breakdown goes as follows:
seen keeps track of the letters we have already encountered.
Scanner goes every character in the string one by one.
If it is a new character (a character which is not in seen), it goes to the result string: seen marks that character as seen.
If it was seen before, we skip it.
Finally, we return the cleaned-up string avoid of repeats.

Basically, this code removes the duplicate characters.
The result will maintain the ordering of the characters as in the original string.
Only the first occurrence of an occurrence of a character is saved.


14.Python function to check if two strings are anagrams?

An anagram is when two words or phrases can be made from the same letters but in a different order.

For example,
listen and silent are made up of the same letters
Another example is that evil and vile are anagrams
hello and world are not they just don't have the same letters

Here is a Python function for checking anagram states
A simple function checks if two strings are anagrams of each other:

def is_anagram(str1, str2):
  return sorted(str1.lower()) == sorted(str2.lower())

Example:
print(is_anagram("Listen", "Silent")) # True
print(is_anagram("Hello", "World")) # False
So:
"Listen" and "Silent" are anagrams
"Hello" and "World" are not

How does this work?
We are using .lower() to create a lowercase version of both strings so that uppercase letters do not influence our result.
Now sorted() arranges the letters of both words in order.
If both sorted versions look the same, it means those words originally held the same letters just shuffled in a different order.


15.Python regex for string matching: simple example?

Regex stands for regular expression. It is a means of searching for specific patterns within text. It helps in finding the words, numbers or even certain pattern in a sentence or a string.
It may check whether a word is incorporated in a sentence, extract all the numbers in a given text or check whether that text starts with a certain phrase.

How to match just a simple word in Python
Say you want to check if a sentence contains the word "apple".
This is how it is done:
import re
text = "I like to eat an apple every day."
pattern = r"apple"
if re.search(pattern, text):
  print("Match found!")
else:
   print("No match.")

What's going on here?
First, we import the re module, which allows us to use regex inside python. Then we set our variable pattern to match the word, in this case, "apple". re.search() checks the whole sentence for that word.
If it finds "apple," it puts out "Match found!" otherwise it says "No match."

More fast examples:
Find all digits (numbers) in a string:
numbers = re.findall(r"\d", "Phone: 123-456-7890")
print(numbers)
# Output: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']

Check whether the string starts with "Hello":
if re.match(r"Hello", "Hello world!"):
   print("Starts with Hello")

Find all words in the sentence:
words = re.findall(r"\w+", "This is a test." )
print(words)
# Output: ['This', 'is', 'a', 'test']

Summarizing:
Regex is where specific text patterns are found.
re.search() is used to search anywhere in the text.
re.findall() can be used to extract all matching parts.


16.How to split a string into words in Python? (split() method)

The simplest means of achieving this would be using the split() method if you have a sentence and want to split it into words.

Example:
text="Learning Python is fun"
words=text.split()
print(words)

Output:
['Learning', 'Python', 'is', 'fun']

Working explanation:
The split() method separates by using spaces as the default separator from the sentence.
So the return is a list of all separate words.
The sentence "Learning Python is fun" now has a total of four separate words.


17.Python join() method: how to use it?

Join() is a method that constructs a single string from the words (or strings) supplied into it, using a delimiter of our choice.
Example: Suppose we have a list of words that we want to join into a sentence.
words = ['Python', 'is', 'fun']
sentence = ' '.join(words)
print(sentence)
Output:
Python is fun
So, here's the one space( ) given in-between the quotation marks, that works as the separator, it goes in-between words while joining.
Thus .join(words) takes everything from that list and sticks it all together with a space in between.
You can have all sorts of separators a comma, dash or even no space in between.

In short:
join() is for joining all the strings accumulated inside one single string.
Interspersed by anything(space, comma, dash or nothing).
Great to form sentences or strings from lists.


19.How to capitalize first letters of each word in Python?

For example, if you have below sentence:
"python is fun"
And you want it to be
"Python Is Fun"
Python gives you a simple way to do it using the title() method.

Example using title():
text = "python is fun"
result = text.title()
print(result)
Output:
Python Is Fun

What is happening here?
The title() method runs through the sentence and capitalizes the first letter of each word and lower case of the remaining ones. It is simple and works fine in most cases.

Want more control?
Sometimes it happens that instead of modifying the case of the whole word from lowercase to uppercase, you want to change just the case of the first letter. You can do this as given below.
text = "python is FUN"
result = ' '.join(word[0].upper() + word[1:] for word in text.split())
print(result)

Output:
Python Is FUN
Here's how it works:
splits the sentence into words.
makes the first letter upper case.
the rest of the word is unchanged.
join puts the words back together with spaces in between.


20.How to check if Python string contains only digits/letters/alphanumeric?

How would you check what a string contains in Python?
There might be cases that you want to test whether a string is strictly numerical, purely alphabetic, or both. Python has built-in methods to do this.

1. If the string actually contains digits only
Use .isdigit() when you want to see if the string is made up of numbers only.
text = "12345"
print(text.isdigit()) # Output: True
This is output True following the string which contains only numbers - no letters or spaces.

2. If the string contains letters only
Use: .isalpha() in which to check whether all characters are letters (no numbers, no spaces, and no symbols).
text = "Hello"
print(text.isalpha()) # Output: True
It will be False if there is even a single space or number.

3. Check whether the string is Alphanumeric
Use .isalnum() in which to check whether the string has letters and/or numbers - but no spaces or special characters.
text = "Python123"
print(text.isalnum()) # Output: True
The above returns True as its containing letters and numbers only.

What if there is a space?
If the string contains a space or symbols (like @,!, etc.), all these methods will give False as a result.
text = "Python 123"
print(text.isalnum()) # Output: False
The space between "Python" and "123" makes it fail.

Quick Recap:
Use .isdigit() → for numbers only
Use .isalpha() → for letters only
Use .isalnum() → for letters and numbers (no spaces or special characters).