Find the Middle Item in a Python List

To find the middle item in a Python List (for both odd and even number of items): Copy my_list = [1, 2, 3, 4, 5]if not my_list: raise ValueError(“List is Empty”)else: mid_item_index = len(my_list) // 2 if len(my_list) % 2 == 0: mid_item_value = my_list[mid_item_index – 1: mid_item_index + 1] else: mid_item_value = my_list[mid_item_index]print(mid_item_value) The … Read more

Count the number of times a character appears in a string in Python

To count the number of times a character appears in a string in Python (both in upper and lower case): Copy my_string = “Sunny Universe”desired_character = “U”count = 0for char in my_string: if char.lower() == desired_character.lower(): count += 1print(count) Here, the letter “U” appears twice (in upper and lower case) : Another approach: Copy my_string … Read more

Count Consonants in a String in Python

To count consonants in a string in Python: Copy vowels = “aeiouAEIOU”my_string = “Hello World!”count = 0for char in my_string: if char.isalpha() and char not in vowels: count += 1print(count) The result: Function to Count Consonants Here is a function to count consonants in a string in Python: Copy def count_consonants(my_string: str) -> int: “”” … Read more

How to Count Vowels in a String in Python

To count vowels in a string in Python: Copy vowels = “aeiouAEIOU”my_string = “Hello Universe”count = 0for char in my_string: if char in vowels: count += 1print(count) The result: Function to count the Vowels Here is a function to count the vowels in a string in Python: Copy def count_vowels(my_string: str) -> int: “”” Function … Read more

How to Reverse a String in Python

To reverse a string in Python: Copy string_example = “Hello World”reversed_string = string_example[::-1]print(reversed_string) The result: Function to reverse a string Here is a function to reverse a string in Python: Copy def reverse_string(my_string: str) -> str: “”” Reverse a string :param my_string: The string you wish to reverse. :return: The reversed string “”” return my_string[::-1]string_example … Read more

Count the Number of Characters in a String in Python (without using the len function)

To count the number of characters in a string without using the “len()” function: Copy my_string = “Hello World”count = 0for _ in my_string: count += 1print(count) The result: Function to count the number of characters Here is a function to count the number of characters in a string: Copy def count_characters(my_string: str) -> int: … Read more