Important code of String
Code 1: To check if a string is a palindrome or not.
s = "A man a plan a canal Panama"
# Remove spaces and convert to lowercase
s = s.replace(" ", "").lower()
# Check if the string is equal to its reverse
if s == s[::-1]:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Code 2: To count the number of vowels in a string.
# Input string
s = "hello world"
# Define the set of vowels
vowels = "aeiouAEIOU"
# Initialize a counter for vowels
vowel_count = 0
# Loop through each character in the string
for char in s:
if char in vowels:
vowel_count += 1
# Print the result
print("Number of vowels:", vowel_count)
Code 3:To count the number of consonants in a string.
# Input string
s = "hello world"
# Define the set of vowels
vowels = "aeiouAEIOU"
# Initialize a counter for consonants
consonant_count = 0
# Loop through each character in the string
for char in s:
if char.isalpha() and char not in vowels:
consonant_count += 1
# Print the result
print("Number of consonants:", consonant_count)
Code 4:To remove duplicates from a string directly in Python.
# Input string
s = "programming"
# Initialize an empty string to store the result
result = " "
# Loop through each character in the original string
for char in s:
# Add the character to result if it's not already in it
if char not in result:
result += char
# Print the result
print("String after removing duplicates:", result)
Code 5:To convert a string to an integer
# Input string
s = "12345"
# Initialize a variable to store the result
result = 0
# Loop through each character in the string
for char in s:
# Convert the character to its corresponding integer value
digit = ord(char) - ord('0')
# Build the number by multiplying the current result by 10 (shifting left) and adding the digit
result = result * 10 + digit
# Print the final integer result
print("Converted integer:", result)
Code 6:Write a function that compresses a string by counting consecutive characters. If
the compressed string is not shorter, return the original string.
# Input string
s = "aaabbcccc"
# Initialize an empty string to store the compressed result
compressed = " "
# Initialize a counter to keep track of character frequencies
count = 1
# Loop through the string, starting from the second character
for i in range(1, len(s)):
# If the current character is the same as the previous one, increment the counter
if s[i] == s[i-1]:
count += 1
else:
# If the current character is different, append the previous character and its count to the
result
compressed += s[i-1] + str(count)
count = 1 # Reset the counter for the new character
# After the loop, add the last character and its count
compressed += s[-1] + str(count)
# If the compressed string is not shorter than the original, return the original string
if len(compressed) < len(s):
print("Compressed string:", compressed)
else:
print("Compressed string is not shorter, returning original:", s)