Python Strings Interview Questions

by | May 12, 2024 | Python | 0 comments

Python Programming Strings Interview Questions

Write a Python program to remove a Specific character from string?

Here’s a Python program to remove a specific character from a string:

def remove_char(text, char):
  """
  Removes a specific character from a string.

  Args:
      text: The input string.
      char: The character to remove.

  Returns:
      The string with the character removed.
  """
  return text.replace(char, "")

# Example usage
text = "Hello, World!"
char_to_remove = "l"

new_text = remove_char(text, char_to_remove)
print(f"Original text: '{text}'")
print(f"Text after removing '{char_to_remove}': '{new_text}'")

Write a Python Program to count occurrence of characters in string?

to count the occurrence of characters in a string:

def char_count(text):
  """
  Counts the occurrence of each character in a string.

  Args:
      text: The input string.

  Returns:
      A dictionary where keys are characters and values are their counts.
  """
  char_counts = {}
  for char in text:
    if char in char_counts:
      char_counts[char] += 1
    else:
      char_counts[char] = 1
  return char_counts

# Example usage
text = "Mississippi"
char_counts = char_count(text)

print("Character counts:")
for char, count in char_counts.items():
  print(f"{char}: {count}")

Write a Python program to count the occurrences of each word in a sentence?

def word_count(sentence):
  """
  Counts the occurrence of each word in a sentence.

  Args:
      sentence: The input sentence as a string.

  Returns:
      A dictionary where keys are words (case-insensitive) and values are their counts.
  """

  # Convert the sentence to lowercase and split it into words
  words = sentence.lower().split()

  # Initialize an empty dictionary to store word counts
  word_counts = {}

  # Count the occurrences of each word
  for word in words:
    if word in word_counts:
      word_counts[word] += 1
    else:
      word_counts[word] = 1

  return word_counts

# Example usage
sentence = "This is a sample sentence to count words."
word_counts = word_count(sentence)

print("Word counts:")
for word, count in word_counts.items():
  print(f"{word}: {count}")

Write a Python program to reverse a string?

def reverse_string(input_string):
 return input_string[::-1]

Write a Python program in to check string is anagrams or not?

def is_anagram(str1, str2):
  """
  Checks if two strings are anagrams (case-insensitive).

  Args:
      str1: The first string.
      str2: The second string.

  Returns:
      True if the strings are anagrams, False otherwise.
  """

  # Convert both strings to lowercase and remove whitespaces
  str1 = str1.lower().replace(" ", "")
  str2 = str2.lower().replace(" ", "")

  # Check if the lengths are equal (anagrams must have the same length)
  if len(str1) != len(str2):
    return False

  # Create a dictionary to store character counts for str1
  char_counts = {}
  for char in str1:
    if char in char_counts:
      char_counts[char] += 1
    else:
      char_counts[char] = 1

  # Check if all characters in str2 can be formed using characters in str1 (and same count)
  for char in str2:
    if char not in char_counts or char_counts[char] == 0:
      return False
    char_counts[char] -= 1

  return True

# Example usage
str1 = "cinema"
str2 = "iceman"

if is_anagram(str1, str2):
  print(f"{str1} and {str2} are anagrams.")
else:
  print(f"{str1} and {str2} are not anagrams.")

Write a Python program to check string is palindrome or not?

Write a Python Program to check given character is digit or not?

Write a Python program to find the most frequent character in a string?

Here are two Python programs to find the most frequent character in a string:

Method 1: Using a dictionary

This method iterates through the string, building a dictionary to store the frequency of each character. The character with the highest count is then identified.

Python

def most_frequent_char(text):
  """
  Finds the most frequent character in a string.

  Args:
      text: The input string.

  Returns:
      A tuple containing the most frequent character and its count.
  """

  char_counts = {}
  for char in text:
    if char not in char_counts:
      char_counts[char] = 0
    char_counts[char] += 1

  # Find the character with the highest count
  most_frequent = max(char_counts, key=char_counts.get)
  count = char_counts[most_frequent]

  return most_frequent, count

# Example usage
text = "Mississippi"
most_frequent, count = most_frequent_char(text)

print(f"The most frequent character in '{text}' is '{most_frequent}' with a count of {count}")

Method 2: Using collections.Counter

This method utilizes the collections.Counter class from the collections module. Counter automatically creates a dictionary to store character counts and provides a built-in method most_common(1) to find the most frequent character.

from collections import Counter

def most_frequent_char(text):
  """
  Finds the most frequent character in a string using Counter.

  Args:
      text: The input string.

  Returns:
      The most frequent character and its count as a tuple.
  """

  char_counts = Counter(text)
  most_frequent = char_counts.most_common(1)[0]  # Get first element of the list

  return most_frequent[0], most_frequent[1]

# Example usage
text = "Mississippi"
most_frequent, count = most_frequent_char(text)

print(f"The most frequent character in '{text}' is '{most_frequent}' with a count of {count}")

Both methods achieve the same result. The first method offers more control over the dictionary creation process, while the second method is more concise using Counter.

Write a Python program to check if a string is a valid email address?

Written by HintsToday Team

Related Posts

Python input function in Detail- interesting usecases

The input() function in Python is primarily used to take input from the user through the command line. While its most common use is to receive text input, it can be used creatively for various purposes. Here are some interesting uses of the input() function along with...

read more

Python Dictionary in detail

What is Dictionary in Python? First of All it is not sequential like List. It is an non-sequential, unordered, redundant and mutable collection as key:value pairs. Keys are always unique but values need not be unique. You use the key to access the corresponding value....

read more

Get the latest news

Subscribe to our Newsletter

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *