0% found this document useful (0 votes)
7 views18 pages

String Tcs

The document contains a series of Python functions that perform various string manipulations, including checking for palindromes, counting vowels and consonants, finding ASCII values, removing vowels and spaces, reversing strings, and more. Each function is accompanied by example usage to demonstrate its functionality. The document serves as a comprehensive guide for string operations in Python.

Uploaded by

priyanshimca24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views18 pages

String Tcs

The document contains a series of Python functions that perform various string manipulations, including checking for palindromes, counting vowels and consonants, finding ASCII values, removing vowels and spaces, reversing strings, and more. Each function is accompanied by example usage to demonstrate its functionality. The document serves as a comprehensive guide for string operations in Python.

Uploaded by

priyanshimca24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Check if a given string is palindrome or not

def is_palindrome(s):

# Convert to lowercase and keep only alphanumeric characters

cleaned = ''.join([Link]() for char in s if [Link]())

# Check if the cleaned string is equal to its reverse

return cleaned == cleaned[::-1]

# Example usage

input_str = input("Enter a string: ")

if is_palindrome(input_str):

print("Yes, it is a palindrome")

else:

print("No, it is not a palindrome")

Example

Enter a string: Madam


Yes, it is a palindrome

Enter a string: Hello


No, it is not a palindrome

Enter a string: A man, a plan, a canal: Panama


Yes, it is a palindrome

1. Count number of vowels, consonants, spaces in String


def count_vowels_consonants_spaces(s):

vowels = "aeiou"

vowel_count = 0

consonant_count = 0

space_count = 0

for char in s:

if [Link]():

space_count += 1

elif [Link](): # Only letters

if [Link]() in vowels:

vowel_count += 1

else:
consonant_count += 1

return vowel_count, consonant_count, space_count

# Take input from the user

input_str = input("Enter a string: ")

v, c, sp = count_vowels_consonants_spaces(input_str)

print("Vowels:", v)

print("Consonants:", c)

print("Spaces:", sp)

EXAMPLE

Enter a string: Hello World 123!

Vowels: 3

Consonants: 7

Spaces: 2

1. Find the ASCII value of a character


# Take input from the user

char = input("Enter a single character: ")

# Ensure only one character is entered

if len(char) != 1:

print("Please enter exactly one character.")

else:

ascii_value = ord(char)

print("ASCII value of", char, "is", ascii_value)

Example

Enter a single character: A

ASCII value of A is 65

Enter a single character: a

ASCII value of a is 97

Enter a single character: $


ASCII value of $ is 36

1. Remove all vowels from the string


# Function to remove vowels

def remove_vowels(s):

vowels = "aeiou"

# Keep only characters that are not vowels

return ''.join(char for char in s if [Link]() not in vowels)

# Take input from the user

input_str = input("Enter a string: ")

result = remove_vowels(input_str)

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

Enter a string: Hello World!

String after removing vowels: Hll Wrld!

1. Remove spaces from a string


# Take input from the user

input_str = input("Enter a string: ")

# Remove all spaces

result = ''.join(char for char in input_str if not [Link]())

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

Enter a string: H e l l o W o r l d

String after removing spaces: HelloWorld

Enter a string: Python 123

String after removing spaces: Python123

1. Remove characters from a string except alphabets


# Take input from the user

input_str = input("Enter a string: ")

# Keep only alphabetic characters

result = ''.join(char for char in input_str if [Link]())


print("String after keeping only alphabets:", result)

Enter a string: Hello World 123!

String after keeping only alphabets: HelloWorld

Enter a string: Python@2026#Exam

String after keeping only alphabets: PythonExam

1. Reverse a String
# Take input from the user

input_str = input("Enter a string: ")

# Reverse the string

reversed_str = input_str[::-1]

print("Reversed string:", reversed_str)

Enter a string: Hello World!

Reversed string: !dlroW olleH

Enter a string: Python123

Reversed string: 321nohtyP

1. Remove brackets from an algebraic expression


# Take input from the user

expr = input("Enter an algebraic expression: ")

# Remove all brackets

cleaned_expr = ''.join(char for char in expr if char not in '(){}[]')

print("Expression after removing brackets:", cleaned_expr)

Enter an algebraic expression: (a+b) - {c*d} + [e/f]

Expression after removing brackets: a+b - c*d + e/f

Enter an algebraic expression: [(x+y)*(z-1)]

Expression after removing brackets: x+y*z-1

1. Sum of the numbers in a String


import re
# Take input from the user

input_str = input("Enter a string: ")

# Find all numbers in the string

numbers = [Link](r'\d+', input_str)

# Convert them to integers and sum

total = sum(int(num) for num in numbers)

print("Sum of numbers in the string:", total)

Enter a string: a1b2c3

Sum of numbers in the string: 6

Enter a string: 100 apples and 50 oranges

Sum of numbers in the string: 150

Enter a string: no numbers here!

Sum of numbers in the string: 0

1. Capitalize first and last character of each word

# Take input from the user

input_str = input("Enter a string: ")

def capitalize_first_last(s):

words = [Link]() # Split by spaces

result = []

for word in words:

if len(word) == 1:

[Link]([Link]())

else:

# Capitalize first and last, keep middle as is


[Link](word[0].upper() + word[1:-1] + word[-1].upper())

return ' '.join(result)

output_str = capitalize_first_last(input_str)

print("Transformed string:", output_str)

Enter a string: hello world

Transformed string: HellO WorlD

Enter a string: a b cd

Transformed string: A B CD

Enter a string: python-exam test_case

Transformed string: PythoN-ExaM Test_CasE

1. Calculate frequency of characters in a string


# Take input from the user

input_str = input("Enter a string: ")

# Dictionary to store frequency

freq = {}

for char in input_str:

if char in freq:

freq[char] += 1

else:

freq[char] = 1

# Print frequency of each character

for char, count in [Link]():

print(f"'{char}': {count}")

Enter a string: Hello World!

'H': 1

'e': 1

'l': 3
'o': 2

' ': 1

'W': 1

'r': 1

'd': 1

'!': 1

Enter a string: 123abc123

'1': 2

'2': 2

'3': 2

'a': 1

'b': 1

'c': 1

1. Find Non-repeating characters of a String


# Take input from the user

input_str = input("Enter a string: ")

# Dictionary to store frequency

freq = {}

for char in input_str:

freq[char] = [Link](char, 0) + 1

# Collect non-repeating characters

non_repeating = [char for char in input_str if freq[char] == 1]

print("Non-repeating characters:", ''.join(non_repeating))

Enter a string: hello world

Non-repeating characters: he wrd

Enter a string: aabbcc

Non-repeating characters:
Enter a string: Python123!

Non-repeating characters: Pytho123!

1. Check if two strings are anagram of each other


# Take input from the user

str1 = input("Enter first string: ")

str2 = input("Enter second string: ")

def are_anagrams(s1, s2):

# Remove non-alphabetic characters and convert to lowercase

cleaned1 = ''.join([Link]() for char in s1 if [Link]())

cleaned2 = ''.join([Link]() for char in s2 if [Link]())

# Sort and compare

return sorted(cleaned1) == sorted(cleaned2)

if are_anagrams(str1, str2):

print("Yes, the strings are anagrams")

else:

print("No, the strings are not anagrams")

Enter first string: Listen

Enter second string: Silent

Yes, the strings are anagrams

Enter first string: a gentleman

Enter second string: elegant man

Yes, the strings are anagrams

Enter first string: Hello

Enter second string: World

No, the strings are not anagrams

1. Return maximum occurring character in the input string


# Take input from the user

input_str = input("Enter a string: ")


# Dictionary to store frequency of each character

freq = {}

for char in input_str:

freq[char] = [Link](char, 0) + 1

# Find character with maximum frequency

max_char = max(freq, key=[Link])

max_count = freq[max_char]

print(f"Maximum occurring character: '{max_char}' with count {max_count}")

Enter a string: hello world

Maximum occurring character: 'l' with count 3

Enter a string: Python123!!

Maximum occurring character: '!' with count 2

Enter a string: aaaBBBccc

Maximum occurring character: 'a' with count 3

1. Remove all duplicates from the input string.


# Take input from the user

input_str = input("Enter a string: ")

# Set to track seen characters

seen = set()

result = []

for char in input_str:

if char not in seen:

[Link](char)

[Link](char)

# Convert list back to string

output_str = ''.join(result)
print("String after removing duplicates:", output_str)

Enter a string: hello world

String after removing duplicates: helo wrd

Enter a string: Python123!!

String after removing duplicates: Python123!

Enter a string: aaaBBBccc

String after removing duplicates: aBBBc //Python is case-sensitive, so 'a' and 'A' are different.

input_str = input("Enter a string: ")

seen = set()

result = []

for char in input_str:

if [Link]() not in seen: # case-insensitive check

[Link]([Link]())

[Link](char)

print("String after removing duplicates:", ''.join(result))

Now for:

aaaBBBccc

the output will be:

aBc
1. Print all the duplicates in the input string .
# Take input
input_str = input("Enter a string: ")

# Count frequency
freq = {}
for char in input_str:
freq[char] = [Link](char, 0) + 1

# Collect duplicates
duplicates = [char for char, count in [Link]() if count > 1]

if duplicates:
print("Duplicate characters:", ', '.join(duplicates))
else:
print("No duplicates found")
Enter a string: hello world
Duplicate characters: l, o

Enter a string: Python123!!


Duplicate characters: 1, 2, 3, !

Enter a string: abc


No duplicates found

Here’s a case-insensitive version to print all duplicates, treating 'A' and 'a' as the same,

# Take input
input_str = input("Enter a string: ")

# Dictionary to store frequency (case-insensitive)


freq = {}
# Dictionary to remember the first occurrence's original character
first_occurrence = {}

for char in input_str:


lower_char = [Link]()
freq[lower_char] = [Link](lower_char, 0) + 1
if lower_char not in first_occurrence:
first_occurrence[lower_char] = char

# Collect duplicates based on case-insensitive count


duplicates = [first_occurrence[char] for char, count in [Link]() if
count > 1]

if duplicates:
print("Duplicate characters (case-insensitive):", ',
'.join(duplicates))
else:
print("No duplicates found")
Enter a string: Hello hELLo World
Duplicate characters (case-insensitive): H, e, l, o
1. Remove characters from first string present in the second string
# Take input from the user

str1 = input("Enter the first string: ")

str2 = input("Enter the second string: ")

# Convert second string to a set for faster lookup

remove_chars = set(str2)

# Build result string by keeping only characters not in second string

result = ''.join(char for char in str1 if char not in remove_chars)

print("Resulting string:", result)

Enter the first string: hello world

Enter the second string: lo

Resulting string: he wrd


Enter the first string: Python123!

Enter the second string: 123!

Resulting string: Python

Enter the first string: abcdef

Enter the second string: xyz

Resulting string: abcdef

1. Change every letter with the next lexicographic alphabet in the given
string
# Take input from the user

input_str = input("Enter a string: ")

def next_alphabet(s):

result = []

for char in s:

if 'a' <= char <= 'z':

# Wrap 'z' to 'a'

[Link]('a' if char == 'z' else chr(ord(char) + 1))

elif 'A' <= char <= 'Z':

# Wrap 'Z' to 'A'

[Link]('A' if char == 'Z' else chr(ord(char) + 1))

else:

# Keep non-letters as is

[Link](char)

return ''.join(result)

output_str = next_alphabet(input_str)

print("Transformed string:", output_str)

Enter a string: hello world

Transformed string: ifmmp xpsme

Enter a string: Python123!

Transformed string: Qzuipo123!


Enter a string: Zebra-Zoo

Transformed string: Afcsb-App

1. Write a program to find the largest word in a given string .


# Take input from the user

input_str = input("Enter a string: ")

# Split the string into words

words = input_str.split()

# Remove punctuation from words for fair comparison

import string

words_cleaned = [''.join(char for char in word if [Link]()) for word in words]

# Find the word with maximum length

if words_cleaned:

max_word = max(words_cleaned, key=len)

print("Largest word:", max_word)

else:

print("No words found in the string")

Enter a string: Hello world from Python!

Largest word: Python

Enter a string: This is a test-case.

Largest word: testcase

Enter a string: 123 45678 90

Largest word: 45678

1. Write a program to sort characters in a string


# Take input from the user

input_str = input("Enter a string: ")

# Sort the characters

sorted_str = ''.join(sorted(input_str))
print("Sorted string:", sorted_str)

Enter a string: Hello World!

Sorted string: !HWdellloor

Enter a string: Python123

Sorted string: 123Phnoty

Enter a string: aaaBBBccc

Sorted string: BBBaaaccc

1. Count number of words in a given string


# Take input from the user

input_str = input("Enter a string: ")

# Split the string into words

words = input_str.split() # split() automatically handles multiple spaces

# Count the words

word_count = len(words)

print("Number of words in the string:", word_count)

Enter a string: Hello world from Python

Number of words in the string: 4

Enter a string: This is a test

Number of words in the string: 4

Enter a string:

Number of words in the string: 0

Enter a string: Hello, world!

Number of words in the string: 2

1. Write a program to find a word in a given string which has the highest
number of repeated letters
# Take input from the user

input_str = input("Enter a string: ")

import string

from collections import Counter

# Split string into words

words = input_str.split()

def max_repeats(word):

# Remove punctuation for accurate letter counting

clean_word = ''.join(char for char in word if [Link]())

if not clean_word:

return 0

freq = Counter(clean_word.lower())

# Count the maximum number of times any letter repeats

return max([Link]())

# Find the word with the highest repeated letters

if words:

word_with_max_repeats = max(words, key=max_repeats)

print("Word with highest repeated letters:", word_with_max_repeats)

else:

print("No words found in the string")

Enter a string: Hello world programming

Word with highest repeated letters: programming

# 'g' repeats 2 times, 'r' repeats 2 times, more than any other word

Enter a string: aaa bb ccc

Word with highest repeated letters: aaa

# 'a' repeats 3 times

Enter a string: Python 123!

Word with highest repeated letters: Python


# All letters appear once, so first word returned

1. Change case of each character in a string


# Take input from the user

input_str = input("Enter a string: ")

# Change case for each character

output_str = input_str.swapcase()

print("String after changing case:", output_str)

Enter a string: Hello World!

String after changing case: hELLO wORLD!

Enter a string: Python123!

String after changing case: pYTHON123!

Enter a string: abcDEF

String after changing case: ABCdef

1. Concatenate one string to another


# Take input from the user

str1 = input("Enter the first string: ")

str2 = input("Enter the second string: ")

# Concatenate the strings

result = str1 + str2

print("Concatenated string:", result)

Enter the first string: Hello

Enter the second string: World

Concatenated string: HelloWorld

Enter the first string: Python

Enter the second string: 123!

Concatenated string: Python 123!


Enter the first string:

Enter the second string: Test

Concatenated string: Test

1. Write a program to find a substring within a string. If found display its


starting position
# Take input from the user

main_str = input("Enter the main string: ")

sub_str = input("Enter the substring to find: ")

# Find the starting position

position = main_str.find(sub_str)

if position != -1:

print(f"Substring found at position: {position}")

else:

print("Substring not found")

Enter the main string: Hello World

Enter the substring to find: World

Substring found at position: 6

Enter the main string: Python123!

Enter the substring to find: 123

Substring found at position: 6

Enter the main string: Hello

Enter the substring to find: abc

Substring not found

1. Reverse words in a string


# Take input from the user

input_str = input("Enter a string: ")

# Split the string into words (split() handles multiple spaces)

words = input_str.split()
# Reverse the list of words

reversed_words = words[::-1]

# Join them back into a string with a single space

output_str = ' '.join(reversed_words)

print("String with reversed words:", output_str)

Enter a string: Hello world from Python

String with reversed words: Python from world Hello

Enter a string: This is a test

String with reversed words: test a is This

Enter a string: Python123!

String with reversed words: Python123!

You might also like