Exploring String in Python : 9 Simple Examples You Can’t Miss

string in python

Dear friends, let’s explore various string manipulation techniques in Python with examples demonstrating the wide range of functionality available with string in Python, along with their corresponding output:

String in Python Example 1 : String Statistics (Upper Case, Lower Case, Digits, Spaces and Delimiters)

def string_statistics(input_string):
    # Initialize counters for different character types
    upper_case_count = 0
    lower_case_count = 0
    digit_count = 0
    space_count = 0
    delimiter_count = 0

    # Define a set of delimiters (you can customize this set)
    delimiters = set(".,!?;:()[]{}<>\"'`~")

    # Iterate through each character in the input string
    for char in input_string:
        if char.isupper():
            upper_case_count += 1
        elif char.islower():
            lower_case_count += 1
        elif char.isdigit():
            digit_count += 1
        elif char.isspace():
            space_count += 1
        elif char in delimiters:
            delimiter_count += 1

    # Return the statistics
    statistics = {
        "Upper Case": upper_case_count,
        "Lower Case": lower_case_count,
        "Digits": digit_count,
        "Spaces": space_count,
        "Delimiters": delimiter_count
    }
    
    return statistics

# Get user input
input_text = input("Enter a text string: ")

# Calculate and display statistics
stats = string_statistics(input_text)

print("\nString Statistics:")
for category, count in stats.items():
    print(f"{category}: {count}")

Output:

Enter a text string: "Codejunction Pro 2023"
String Statistics:
Upper Case: 2
Lower Case: 13
Digits: 4
Spaces: 2
Delimiters: 2

String in Python Example 2 : Input a String & Check for Palindrome

def is_palindrome(input_string):
    # Remove spaces and convert the input string to lowercase for comparison
    clean_string = input_string.replace(" ", "").lower()
    
    # Compare the cleaned string with its reverse to check for palindromes
    if clean_string == clean_string[::-1]:
        return True
    else:
        return False

# Get user input
user_input = input("Enter a string to check for palindrome: ")

# Check if the input string is a palindrome
if is_palindrome(user_input):
    print(f'"{user_input}" is a palindrome!')
else:
    print(f'"{user_input}" is not a palindrome.')

Output:

Enter a string to check for palindrome: radar
"radar" is a palindrome!

Enter a string to check for palindrome: radix
"radix" is not a palindrome.

String in Python Example 3 : Print Alternate Character in Uppercase

def alternate_uppercase(input_string):
    # Initialize an empty string to store the result
    result = ""
    
    # Iterate through the characters of the input string
    for index, char in enumerate(input_string):
        # Check if the current character is at an even index (0-based)
        if index % 2 == 0:
            # If it's at an even index, convert it to uppercase and add it to the result
            result += char.upper()
        else:
            # If it's at an odd index, add it to the result as it is (in its original case)
            result += char

    return result

# Get user input
user_input = input("Enter a string: ")

# Call the function to print alternate characters in uppercase
result = alternate_uppercase(user_input)

# Display the result
print(f"Alternate characters in uppercase: {result}")

Output:

Enter a string: Codejunction
Alternate characters in uppercase: CoDeJuNcTiOn

String in Python Example 4 : Count Vowels in a String

def count_vowels(input_string):
    # Define a set of vowels in both uppercase and lowercase
    vowels = set("AEIOUaeiou")
    
    # Initialize a counter for counting vowels
    vowel_count = 0
    
    # Iterate through the characters of the input string
    for char in input_string:
        if char in vowels:
            # If the character is in the set of vowels, increment the vowel count
            vowel_count += 1

    return vowel_count

# Get user input
user_input = input("Enter a string: ")

# Call the function to count vowels in the input string
result = count_vowels(user_input)

# Display the result
print(f"Number of vowels in the string: {result}")

Output:

Enter a string: Codejunction Pro
Number of vowels in the string: 6

String in Python Example 5 : Remove Punctuation Character in a String

import string

def remove_punctuation(input_string):
    # Define a set of punctuation characters using string.punctuation
    punctuation_set = set(string.punctuation)
    
    # Initialize an empty string to store the result
    result = ""
    
    # Iterate through the characters of the input string
    for char in input_string:
        if char not in punctuation_set:
            # If the character is not in the set of punctuation characters, add it to the result
            result += char

    return result

# Get user input
user_input = input("Enter a string: ")

# Call the function to remove punctuation from the input string
result = remove_punctuation(user_input)

# Display the result
print(f"String without punctuation: {result}")

Output:

Enter a string: "He said, 'password' is A!b@c#_%%"
String without punctuation: He said password is Abc

String in Python Example 6 : Sorting Names

def sort_names(name_list):
    # Use the sorted() function to sort the names alphabetically
    sorted_names = sorted(name_list)
    return sorted_names

# Get user input for names
num_names = int(input("How many names do you want to sort? "))
names = []

for i in range(num_names):
    name = input(f"Enter name {i + 1}: ")
    names.append(name)

# Call the function to sort the names
sorted_names = sort_names(names)

# Display the sorted names
print("Sorted Names:")
for name in sorted_names:
    print(name)

Output:

How many names do you want to sort? 6
Enter name 1: Jim
Enter name 2: John
Enter name 3: Scott
Enter name 4: Anil
Enter name 5: Bob
Enter name 6: Vinod
Sorted Names:
Anil
Bob
Jim
John
Scott
Vinod

String in Python Example 7 : Print Words in a Sentence in Reverse Order

def reverse_words_in_sentence(sentence):
    # Split the sentence into words using whitespace as the delimiter
    words = sentence.split()
    
    # Reverse the list of words
    reversed_words = list(reversed(words))
    
    # Join the reversed words to form a new sentence
    reversed_sentence = ' '.join(reversed_words)
    
    return reversed_sentence

# Get user input for the sentence
user_input = input("Enter a sentence: ")

# Call the function to reverse the words in the sentence
reversed_sentence = reverse_words_in_sentence(user_input)

# Display the reversed sentence
print("Reversed Sentence:")
print(reversed_sentence)

Output:

Enter a sentence: Python is OOP Language
Reversed Sentence:
Language OOP is Python

String in Python Example 8 : Calculate Sum of Digits in a String

def sum_of_digits(input_string):
    # Initialize a variable to store the sum of digits
    digit_sum = 0
    
    # Iterate through the characters in the input string
    for char in input_string:
        if char.isdigit():
            # If the character is a digit, convert it to an integer and add it to the sum
            digit_sum += int(char)

    return digit_sum

# Get user input
user_input = input("Enter a string: ")

# Call the function to calculate the sum of digits in the input string
result = sum_of_digits(user_input)

# Display the result
print(f"Sum of digits in the string: {result}")

Output:

Enter a string: Hello123World
Sum of digits in the string: 6

String in Python Example 9 : Rotate String Characters in Cyclic Order

st = input("Enter a String:")

for i in range(0, len(st)):
    print(st[i:], end="")
    print(st[0:i])

Output:

Enter a String:hello
hello
elloh
llohe
lohel
ohell

Conclusion

String in python are not just tools, but a creative medium for shaping data, communicating ideas, and bringing projects to life. Exploring strings in Python is just the beginning of the journey. As you continue with Python, use this newfound knowledge as a foundation to build coding adventures one character at a time. Happy coding!

Leave a Reply

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