Python strings can be defined by enclosing them within either single quotes (”) or double quotes (“”). For example, ‘Hello World’ and “Python” are both valid string literals. This flexibility allows programmers to choose the quotation marks that best suit their needs. In this post, we will explore 10 different python string examples and explain each method.
Python String Examples
1. Word Counter
Count the number of occurrences of each word in a given text.
def word_counter(text):
words = text.split()
count_dict = {}
for word in words:
word = word.lower().strip(",.!?()[]{}")
count_dict[word] = count_dict.get(word, 0) + 1
for word, count in count_dict.items():
print(f"{word}: {count}")
text_sample = """Python is a great programming language.
Python is also used for web development. I love Python!"""
word_counter(text_sample)
2. Palindrome Checker
Check if the provided string is a palindrome.
def is_palindrome(s):
s = ''.join([char for char in s if char.isalnum()]).lower()
return s == s[::-1]
test_str = "A man, a plan, a canal, Panama!"
print(is_palindrome(test_str))
3. Anagram Checker
Check if two strings are anagrams.
def are_anagrams(s1, s2):
return sorted(s1.replace(" ", "").lower()) == sorted(s2.replace(" ", "").lower())
str1 = "Listen"
str2 = "Silent"
print(are_anagrams(str1, str2))
4. Caesar Cipher
Encrypt a string using the Caesar cipher.
def caesar_cipher(s, shift):
result = ""
for char in s:
if char.isalpha():
shifted = ord(char) + shift
if char.islower():
if shifted > ord('z'):
shifted -= 26
elif shifted > ord('Z'):
shifted -= 26
result += chr(shifted)
else:
result += char
return result
plaintext = "Hello, World!"
encrypted = caesar_cipher(plaintext, 3)
print(encrypted)
5. Vowel Counter
Count the number of vowels in a string.
def count_vowels(s):
vowels = 'aeiou'
count = 0
for char in s.lower():
if char in vowels:
count += 1
return count
sentence = "The quick brown fox jumps over the lazy dog."
print(count_vowels(sentence))
6. Title Case Converter
Convert a string to title case (first letter of each word capitalized).
def title_case(s):
return ' '.join([word.capitalize() for word in s.split()])
text = "this is a sample text."
print(title_case(text))
7. String Reverser
Reverse each word in a string.
def reverse_words(s):
return ' '.join([word[::-1] for word in s.split()])
sentence = "Hello from the other side"
print(reverse_words(sentence))
8. Acronym Generator
Generate an acronym from a given string.
def generate_acronym(s):
return ''.join([word[0].upper() for word in s.split()])
phrase = "As Soon As Possible"
print(generate_acronym(phrase))
9. Leetspeak Converter
Convert a string to leetspeak (1337speak).
def to_leetspeak(s):
leet_dict = {
'a': '4', 'b': '8', 'c': '<', 'e': '3',
'g': '9', 'h': '#', 'i': '1', 'o': '0',
's': '$', 't': '7', 'z': '2'
}
return ''.join([leet_dict.get(char, char) for char in s.lower()])
message = "Hello, Coders!"
print(to_leetspeak(message))
10. Initials Extractor
Extract the initials from a full name.
def extract_initials(name):
return '.'.join([word[0].upper() for word in name.split()]) + '.'
full_name = "Alan Turing"
print(extract_initials(full_name))
Each of these use cases demonstrates different operations and manipulations on Python strings.