Common string questions
Find the first non-repeating character in a string
def first_non_repeating_char(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in s:
if char_count[char] == 1:
return char
return None
Find number of vowels and consonants in a string
def count_vowels_consonants(s):
vowels = 'aeiou'
vowels_count = 0
consonants_count = 0
for char in s:
if char.isalpha(): # built-in method to check if a character is a letter
if char.lower() in vowels:
vowels_count += 1
else:
consonants_count += 1
return vowels_count, consonants_count
Check if a string is a palindrome
def is_palindrome(s):
return s == s[::-1]
Count the number of words in a string
def count_words(s):
return len(s.split())
Reverse words in a string
def reverse_words(s):
return ' '.join(s.split()[::-1])
Check if a string is an anagram of another string
def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)