0% found this document useful (0 votes)
15 views3 pages

Python String Manipulation Exercises

The document contains various Python coding exercises and their expected outputs. It includes tasks such as string manipulation, counting characters, reversing words, and removing duplicates. Each exercise is followed by example code snippets and their results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views3 pages

Python String Manipulation Exercises

The document contains various Python coding exercises and their expected outputs. It includes tasks such as string manipulation, counting characters, reversing words, and removing duplicates. Each exercise is followed by example code snippets and their results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

In [1]: # What will be the output of the following code?

s = "PythonProgramming"
print(s[2:10:2])

toPo

In [2]: # What does the following code output?


s = "hello world"
print([Link]().swapcase())

hELLO WORLD

In [3]: # Write a Python code to count the occurrences of a given character in a string.

name=input("enter your name:")


char= input("enter a letter you want to count:")
count=0
for i in name:
if i == char:
count= count+1
print(count)

enter your name:saurav


enter a letter you want to count:a
2

In [ ]: # What will be the output of the following?


name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

In [2]: # Write a code to check if a given string is a palindrome (ignoring case and spaces).

In [16]: # Given a string sentence, write a Python program to reverse the words but keep their or
sentence= "Hello how are you"
reverse=[]
sentence= [Link]()
for i in sentence:
[Link](i[::-1])
reverse=" ".join(reverse)
print(reverse)

olleH woh era uoy

In [5]: # Write a Python code to find the longest word in a sentence.


sentence = "Find the longest word in this sentence"
words = [Link]() # Split the sentence into a list of words

longest_word = "" # Initialize the longest word as an empty string

# Iterate through each word in the list


for word in words:
if len(word) > len(longest_word): # Compare the length of the word with the longest
longest_word = word # Update the longest word

print("The longest word is:", longest_word)

The longest word is: sentence

In [8]: # Write a Python program to remove duplicate characters from a string while maintaining
my_string = "programming"
result = ""
seen = set() # A set to keep track of characters we've already seen

# Iterate through each character in the string


for char in my_string:
if char not in seen:
result += char # Add to result if not seen already
[Link](char) # Mark the character as seen

print("String after removing duplicates:", result)

String after removing duplicates: progamin

In [6]: # Write a code that compresses a string using the counts of repeated characters.
# Input: aabcccccaaa
# Output: a2b1c5a3
s = "aabcccccaaa"
s1 = ""
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
s1 += s[i - 1] + str(count)
count = 1
s1 += s[-1] + str(count)

print(s1)

a2b1c5a3

In [4]: # Write a Python code that returns the first non-repeating character in a given string.
s= input("enter any word:")
s1=""
for i in s:
if [Link](i)<2:
s1=s1+i
first_np=s1[0]
print(first_np)

enter any word:saurav


s

In [5]: # Find the length of a given string without using the len() function
my_string = "Hello, World!"
count = 0

for char in my_string:


count += 1

print(count) # Output: 13

13

In [18]: # Extract username from a given email.


# Eg if the email is Saurav24Gupta@[Link]
# then the username should be Saurav24Gupta
email= input("enter your email")
user_id= [Link]("@")
user_id= email[:[Link]("@")]
print(user_id)

enter your emailSaurav24Gupta@[Link]


Saurav24Gupta

In [20]: # Count the frequency of a particular character in a provided string.


# Eg 'hello how are you' is the string, the frequency of h in this string is 2.
string= "hello how are you"
char= input("enter a character")
for i in string:
count= [Link](char)
print(count)

enter a charactero
3

In [11]: # Write a program which can remove a particular character from a string.

In [12]: # Write a program to count the number of words in a string without split()

In [13]: # Write a python program to convert a string to title case without using the title()

In [14]: # Write a program that can convert an integer to string.

You are given a string s consisting of lowercase


English letters. Your task is to perform the
following transformation:
Replace every vowel in the string ('a', 'e', 'i', 'o', 'u') with its uppercase form.

Remove all duplicate characters while preserving the original order.

Reverse the final string after processing steps 1 and 2.

In [15]: #"s = "hello"

#o/p= "OlEh"

You are given a string s consisting of lowercase


English letters. Your task is to remove all
characters at odd indices and return the modified
string.
In [17]: # s = "hacker"
# "hce"

In [ ]:

Common questions

Powered by AI

Initialize a counter to zero. Iterate through each character in the string, incrementing the counter for each character encountered. The counter then reflects the total number of characters in the string, equal to its length .

Initialize a counter at zero. Iterate over each character in the string, compare it with the target character, and increment the counter upon each match. This counts the total occurrences of the character in the string .

To check if a string is a palindrome while ignoring case and spaces, convert the string to a consistent case, remove spaces, and compare the string to its reverse. If they are the same, the string is a palindrome .

First, replace vowels ('a', 'e', 'i', 'o', 'u') with their uppercase equivalents. Next, use a set to remove duplicate characters while maintaining order. Finally, reverse this processed string to complete the transformation .

Split the sentence into words, reverse each word individually, and then join them back into a string. This reverses the characters in each word but maintains the overall word order in the sentence .

To remove duplicates from a string while maintaining order, use a set to track seen characters and append unseen characters to the result string. This ensures each character is added only once while preserving the original order .

Extract the username by finding the index of the '@' symbol and slicing the email string up to this index. This slice represents the username of the email address .

To find the first non-repeating character, iterate over the string, counting occurrences of each character. Append characters appearing less than twice to a new string, then print the first character of this new string, which represents the first non-repeating character .

The code outputs 'a2b1c5a3'. It iterates through the string, counting consecutive duplicate characters and appending the character along with its count to the result string when a different character is encountered or the end of the string is reached .

Split the sentence into words and iterate through each word. If the length of the current word is greater than the longest tracked word, update the longest tracked word. Continue this process until all words are compared. The longest word found is then printed .

You might also like