Enhance your Python string manipulation skills through valuable code examples, which offer insights into various operations in Python programming.

  • It accepts console entries and removes specified characters from them.
  • The second program finds the first and second-highest numbers in a list.
  • The third program counts consecutive characters in a string.
Python string manipulation programs
Photo by Krivec Ales on Pexels.com

01. Remove the Character from the String Entered From the Console

inp = input("Enter the string: ")
ch = input("Enter the character to remove: ")

# Using str.replace() to remove all occurrences of the character
res = inp.replace(ch, "")

print(res)

output

inp=abc
char entered=a
out=bc

02. Find first First-highest and Second-Highest

Use the sorted method to sort in reverse order.

l = [10, 90, 40, 60, 20]

# Sort the list in descending order
sorted_list = sorted(l, reverse=True)

# First highest number
first_highest = sorted_list[0]

# Second highest number
second_highest = sorted_list[1]

print(f"First highest number: {first_highest}")
print(f"Second highest number: {second_highest}")

Output

First heighest: 90
Second heighest: 60

03. String Character/Word Count

Example:1 Char count

s = "aabbbccccaaaaa"

output = ""
count = 1

for i in range(1, len(s)):
    # Check if the current character is the same as the earlier character
    if s[i] == s[i - 1]:
        count += 1
    else:
        output += s[i - 1] + str(count)
        count = 1

# Add the last character and its count
output += s[-1] + str(count)

print(output)

Output

a2b3c4a5

Example:2 Word count

a = "I am here I am fine"

# Split the string into words
words = a.split(" ")

# Initialize an empty dictionary to store word counts
word_count = {}

# Iterate through each word in the list
for word in words:
    # If the word is already in the dictionary, increment its count
    if word in word_count:
        word_count[word] +=1
    # If the word is not in the dictionary, add it with count 1
    else:
        word_count[word] = 1

# Print the word counts
for word, count in word_count.items():
    print(f"{word} - {count}")

Output

I - 2
am - 2
here - 1
fine - 1


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Example 3: Char count using collections

from collections import Counter

a = "abcabc"
count_dict = Counter(a)
print(count_dict)
out = ""

# Iterate through sorted characters to keep order
for char in sorted(count_dict):
    out += char + str(count_dict[char])

print(out)

Output

Counter({'a': 2, 'b': 2, 'c': 2})
a2b2c2


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Example 4: Last word to bring the first position and keep the remaining string the same

a="My Name is Srini Here"

b=a.split(" ")

o=b[-1]+ " " + " ".join(b[0:len(b)-1]) 

print(o)

Output

Here My Name is Srini


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Conclusion

These python string manipulation programs offer a deeper understanding of list sorting and character counting in Python. By working through these examples, you’ll gain practical experience and develop your programming skills.