[Go to site: main page, start]

0% found this document useful (0 votes)
6 views19 pages

String Programs in Python

The document contains a collection of Python programs that demonstrate various string and list manipulation techniques. It includes functionalities such as counting characters, reversing strings, checking for palindromes, and handling lists through operations like appending, inserting, and slicing. Each program is accompanied by example input and output to illustrate its functionality.

Uploaded by

drishtirajora01
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)
6 views19 pages

String Programs in Python

The document contains a collection of Python programs that demonstrate various string and list manipulation techniques. It includes functionalities such as counting characters, reversing strings, checking for palindromes, and handling lists through operations like appending, inserting, and slicing. Each program is accompanied by example input and output to illustrate its functionality.

Uploaded by

drishtirajora01
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

STRING PROGRAMS IN PYTHON

1. Count the Length of a String


# Program
s = input("Enter a string: ")
print("Length of string:", len(s))

# Output
Enter a string: Queen
Length of string: 5

2. Reverse a String
# Program
s = input("Enter a string: ")
rev = s[::-1]
print("Reversed string:", rev)

# Output
Enter a string: hello
Reversed string: olleh

3. Check Whether a String is Palindrome


# Program
s = input("Enter a string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

# Output
Enter a string: madam
Palindrome

4. Count Vowels and Consonants


# Program

s = input("Enter a string: ")

vowels = 0
consonants = 0
for ch in [Link]():
if ch in "aeiou":
vowels += 1
elif [Link]():
consonants += 1
print("Vowels:", vowels)
print("Consonants:", consonants)

# Output
Enter a string: Queen
Vowels: 3
Consonants: 2

5. Count Uppercase, Lowercase, Digits, and Special Characters


# Program
s = input("Enter a string: ")
u = l = d = sp = 0
for ch in s:
if [Link]():
u += 1
elif [Link]():
l += 1
elif [Link]():
d += 1
else:
sp += 1
print("Uppercase:", u)
print("Lowercase:", l)
print("Digits:", d)
print("Special characters:", sp)

# Output
Enter a string: Bhumi123@
Uppercase: 1
Lowercase: 4
Digits: 3
Special characters: 1

6. Count Total Words in a Sentence


# Program
s = input("Enter a sentence: ")
words = [Link]()
print("Total words:", len(words))

# Output
Enter a sentence: I love Python
Total words: 3
7. Replace All Spaces with Hyphens
# Program
s = input("Enter a sentence: ")
print("Modified:", [Link](" ", "-"))

# Output
Enter a sentence: Python is fun
Modified: Python-is-fun

8. Count Occurrences of a Substring


# Program
s = input("Enter a string: ")
sub = input("Enter substring: ")
print("Occurrences:", [Link](sub))

# Output
Enter a string: banana
Enter substring: an
Occurrences: 2

9. Find the Longest Word in a Sentence


# Program
s = input("Enter a sentence: ")
words = [Link]()
longest = max(words, key=len)
print("Longest word:", longest)

# Output
Enter a sentence: Python is powerful
Longest word: powerful

10. Remove All Vowels from a String


# Program
s = input("Enter a string: ")
vowels = "aeiouAEIOU"
result = ""
for ch in s:
if ch not in vowels:
result += ch
print("After removing vowels:", result)

# Output
Enter a string: Beautiful
After removing vowels: Btfl
11. Print Frequency of Each Character
# Program
s = input("Enter a string: ")
for ch in set(s):
print(ch, "=", [Link](ch))

# Output
Enter a string: hello
l = 2
o = 1
e = 1
h = 1

12. Convert String into List and List into String


# Program
s = input("Enter a sentence: ")
lst = [Link]()
print("List form:", lst)
print("String form:", " ".join(lst))

# Output
Enter a sentence: Python is cool
List form: ['Python', 'is', 'cool']
String form: Python is cool

13. Check Whether Two Strings Are Anagrams


# Program
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")
if sorted(s1) == sorted(s2):
print("Anagram")
else:
print("Not Anagram")

# Output
Enter first string: listen
Enter second string: silent
Anagram
14. Remove Punctuation Marks
# Program
s = input("Enter a string: ")
punct = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
result = ""
for ch in s:
if ch not in punct:
result += ch
print("After removing punctuation:", result)

# Output
Enter a string: Hello!!! How are you?
After removing punctuation: Hello How are you

15. Print ASCII Value of Each Character


# Program
s = input("Enter a string: ")
for ch in s:
print(ch, "=", ord(ch))

# Output
Enter a string: ABC
A = 65
B = 66
C = 67

16. Convert Lowercase to Uppercase and Vice Versa (Without Built-ins)


# Program
s = input("Enter a string: ")
res = ""
for ch in s:
if 'a' <= ch <= 'z':
res += chr(ord(ch) - 32)
elif 'A' <= ch <= 'Z':
res += chr(ord(ch) + 32)
else:
res += ch
print("Converted string:", res)

# Output
Enter a string: PyThOn
Converted string: pYtHoN
17. Sort Words of a Sentence Alphabetically
# Program
s = input("Enter a sentence: ")
words = [Link]()
[Link]()
print("Sorted words:", words)

# Output
Enter a sentence: banana apple mango
Sorted words: ['apple', 'banana', 'mango']

18. Find the Most Repeated Word in a Sentence


# Program
s = input("Enter a sentence: ")
words = [Link]()
most = max(words, key=[Link])
print("Most repeated word:", most)

# Output
Enter a sentence: this is is a test test test
Most repeated word: test

19. Check If String is Symmetric


# Program
s = input("Enter a string: ")
mid = len(s)//2
if s[:mid] == s[mid:]:
print("Symmetric")
else:
print("Not Symmetric")

# Output
Enter a string: abab
Symmetric

20. Remove Duplicate Characters from String


# Program
s = input("Enter a string: ")
result = ""
for ch in s:
if ch not in result:
result += ch
print("After removing duplicates:", result)
# Output
Enter a string: programming
After removing duplicates: progamin
1. Print first and last character of a string
s = input("Enter string: ")
print("First character:", s[0])
print("Last character:", s[-1])
Output:
Enter string: Python
First character: P
Last character: n
2. Print middle character(s) of a string
s = input("Enter string: ")
mid = len(s) // 2
if len(s) % 2 == 0:
print("Middle characters:", s[mid-1:mid+1])
else:
print("Middle character:", s[mid])
Output:
Enter string: Queen
Middle character: e
Enter string: Hello
Middle character: l
Enter string: Good
Middle characters: oo
3. Print only alternate characters
s = input("Enter string: ")
print("Alternate characters:", s[::2])
Output:
Enter string: Computer
Alternate characters: Cmue
4. Reverse a string using slicing
s = input("Enter string: ")
print("Reversed string:", s[::-1])
Output:
Enter string: Queen
Reversed string: neeuQ
5. Extract first and last word from a sentence
s = input("Enter sentence: ")
words = [Link]()
print("First word:", words[0])
print("Last word:", words[-1])

Output:

Enter sentence: Python is amazing


First word: Python
Last word: amazing

6. Count number of words starting with a vowel


s = input("Enter sentence: ")
words = [Link]()
count = 0
for w in words:
if w[0].lower() in 'aeiou':
count += 1
print("Words starting with vowels:", count)
Output:
Enter sentence: Apple is an orange fruit
Words starting with vowels: 4
7. Swap first and last word of a sentence
s = input("Enter sentence: ")
words = [Link]()
words[0], words[-1] = words[-1], words[0]
print("After swapping:", " ".join(words))
Output:
Enter sentence: I love Python
After swapping: Python love I
1. Count vowels using function
def count_vowels(s):
vowels = "aeiouAEIOU"
c = 0
for ch in s:
if ch in vowels:
c += 1
return c

text = input("Enter string: ")


print("Number of vowels:", count_vowels(text))
Output:
Enter string: Education
Number of vowels: 5
2. Check palindrome using function
def is_palindrome(s):
return s == s[::-1]

s = input("Enter string: ")


print("Palindrome:", is_palindrome(s))
Output:
Enter string: madam
Palindrome: True
Enter string: queen
Palindrome: False
3. Count total words using function
def word_count(s):
return len([Link]())
s = input("Enter sentence: ")
print("Total words:", word_count(s))
Output:
Enter sentence: Python is fun
Total words: 3
4. Remove spaces using function
def remove_spaces(s):
return [Link](" ", "")
s = input("Enter string: ")
print("Without spaces:", remove_spaces(s))
Output:
Enter string: I love coding
Without spaces: Ilovecoding
5. Count digits using function
def count_digits(s):
c = 0
for ch in s:
if [Link]():
c += 1
return c
s = input("Enter string: ")
print("Number of digits:", count_digits(s))
Output:
Enter string: Python123
Number of digits: 3
1. Count Frequency of Each Character (Dictionary Style)
s = input("Enter string: ")
freq = {}
for ch in s:
freq[ch] = [Link](ch, 0) + 1
print("Character frequencies:", freq)
Output:
Enter string: hello
Character frequencies: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
2. Count Number of Words, Digits, Alphabets, and Special Characters
s = input("Enter string: ")
alpha = digit = special = space = 0
for ch in s:
if [Link]():
alpha += 1
elif [Link]():
digit += 1
elif [Link]():
space += 1
else:
special += 1
print("Alphabets:", alpha)
print("Digits:", digit)
print("Spaces:", space)
print("Special characters:", special)
Output:
Enter string: Hello 123!
Alphabets: 5
Digits: 3
Spaces: 1
Special characters: 1
3. Remove All Punctuation Marks
s = input("Enter string: ")
punct = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
result = ""
for ch in s:
if ch not in punct:
result += ch
print("Without punctuation:", result)
Output:
Enter string: Hello, how are you?
Without punctuation: Hello how are you
4. Count the Frequency of Each Word in a Sentence
s = input("Enter sentence: ").lower().split()
freq = {}
for word in s:
freq[word] = [Link](word, 0) + 1
print("Word frequency:", freq)
Output:
Enter sentence: this is is test
Word frequency: {'this': 1, 'is': 2, 'test': 1}
5. Check if Two Strings are Anagrams
a = input("Enter first string: ")
b = input("Enter second string: ")
if sorted([Link]()) == sorted([Link]()):
print("Anagram")
else:
print("Not anagram")
Output:
Enter first string: listen
Enter second string: silent
Anagram
6. Find the Longest Word in a Sentence
s = input("Enter sentence: ").split()
longest = max(s, key=len)
print("Longest word:", longest)
Output:
Enter sentence: Python is amazing
Longest word: amazing
7. Count Occurrence of Each Vowel
s = input("Enter string: ").lower()
for v in "aeiou":
print(v, ":", [Link](v))
Output:
Enter string: Education
a : 1
e : 1
i : 1
o : 1
u : 1

8. Remove Duplicates from a String


s = input("Enter string: ")
result = ""
for ch in s:
if ch not in result:
result += ch
print("String after removing duplicates:", result)
Output:
Enter string: banana
String after removing duplicates: ban
9. Sort Words Alphabetically
s = input("Enter sentence: ").split()
[Link]()
print("Sorted words:", " ".join(s))
Output:
Enter sentence: mango apple banana
Sorted words: apple banana mango
10. Replace Each Space with ‘*’
s = input("Enter string: ")
print([Link](" ", "*"))
Output:
Enter string: Hello world
Hello*world
11. Print Words Starting with a Particular Letter
s = input("Enter sentence: ").split()
letter = input("Enter starting letter: ").lower()
for word in s:
if [Link]().startswith(letter):
print(word)
Output:
Enter sentence: Sun sets slowly in summer
Enter starting letter: s
Sun
sets
slowly
summer
12. Count Total Lines, Words, and Characters in a Paragraph (multiline input)
text = ""
print("Enter paragraph (type END to stop):")
while True:
line = input()
if line == "END":
break
text += line + " "

lines = [Link]('\n') + 1
words = len([Link]())
chars = len(text)
print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)
13. Check if a String is Symmetrical
s = input("Enter string: ")
mid = len(s) // 2
if s[:mid] == s[mid:]:
print("Symmetrical")
else:
print("Not symmetrical")
Output:
Enter string: abab
Symmetrical

LIST HANDLING – COMPLETE PROGRAMS

1. Create a List and Display Elements


lst = [10, 20, 30, 40]
print("List:", lst)
Output:
List: [10, 20, 30, 40]

2. Input a List Using eval()

lst = eval(input("Enter a list: "))


print("List entered:", lst)
Output:
Enter a list: [2, 4, 6, 8]
List entered: [2, 4, 6, 8]

3. Input a List Using split()


lst = input("Enter numbers: ").split()
print("List:", lst)
Output:
Enter numbers: 10 20 30
List: ['10', '20', '30']

4. Accessing Elements (Indexing)


lst = [10, 20, 30, 40]
print("First element:", lst[0])
print("Last element:", lst[-1])
Output:
First element: 10
Last element: 40

5. Slicing a List
lst = [10, 20, 30, 40, 50]
print(lst[1:4])
print(lst[::-1])
Output:
[20, 30, 40]
[50, 40, 30, 20, 10]

6. List Concatenation & Repetition


a = [1, 2]
b = [3, 4]
print(a + b)
print(a * 3)
Output:
[1, 2, 3, 4]
[1, 2, 1, 2, 1, 2]
7. Check Membership
lst = [5, 10, 15, 20]
print(10 in lst)
print(25 not in lst)
Output:
True
True

8. List Comparison
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
Output:
True

9. Append & Extend


lst = [10, 20]
[Link](30)
[Link]([40, 50])
print(lst)
Output:
[10, 20, 30, 40, 50]

10. Insert and Pop


lst = [10, 20, 30]
[Link](1, 15)
print("After insert:", lst)
[Link](2)
print("After pop:", lst)
Output:
After insert: [10, 15, 20, 30]
After pop: [10, 15, 30]

11. Remove and Clear


lst = [10, 20, 30, 40]
[Link](30)
print("After remove:", lst)
[Link]()
print("After clear:", lst)
Output:
After remove: [10, 20, 40]
After clear: []

12. Traversing a List


lst = [5, 10, 15]
for i in range(len(lst)):
print(lst[i])
Output:
5
10
15

13. Find Sum, Max, Min


lst = [3, 5, 7, 2]
print("Sum:", sum(lst))
print("Max:", max(lst))
print("Min:", min(lst))
Output:
Sum: 17
Max: 7
Min: 2

14. Reverse and Sort


lst = [30, 10, 40, 20]
[Link]()
print("Sorted:", lst)
[Link]()
print("Reversed:", lst)
Output:
Sorted: [10, 20, 30, 40]
Reversed: [40, 30, 20, 10]
15. Count Occurrences

lst = [1, 2, 2, 3, 2]
print("Count of 2:", [Link](2))
Output:
Count of 2: 3

16. Copy vs Reference


a = [1, 2, 3]
b = a
[Link](4)
print("a =", a)
print("b =", b)
Output:
a = [1, 2, 3, 4]
b = [1, 2, 3, 4]

17. Copy Properly


a = [1, 2, 3]
b = [Link]()
[Link](4)
print("a =", a)
print("b =", b)
Output:
a = [1, 2, 3]
b = [1, 2, 3, 4]

18. Merge Two Lists


a = [1, 2]
b = [3, 4]
c = a + b
print("Merged list:", c)
Output:
Merged list: [1, 2, 3, 4]

19. Separate Even and Odd Numbers


lst = [1, 2, 3, 4, 5, 6]
even = []
odd = []
for i in lst:
if i % 2 == 0:
[Link](i)
else:
[Link](i)
print("Even:", even)
print("Odd:", odd)
Output:
Even: [2, 4, 6]
Odd: [1, 3, 5]

20. Remove Duplicates


lst = [1, 2, 2, 3, 1, 4]
new = []
for i in lst:
if i not in new:
[Link](i)
print("Without duplicates:", new)
Output:
Without duplicates: [1, 2, 3, 4]

21. Convert String → List


s = "Hello World"
lst = [Link]()
print(lst)
Output:
['Hello', 'World']

22. Convert List → String


lst = ['Python', 'is', 'fun']
s = " ".join(lst)
print(s)
Output:
Python is fun

23. Find 2nd Largest Number


lst = [10, 25, 15, 40]
[Link]()
print("Second largest:", lst[-2])
Output:
Second largest: 25

24. Frequency of Each Element


lst = [2, 3, 2, 4, 3, 2]
freq = {}
for i in lst:
freq[i] = [Link](i, 0) + 1
print(freq)
Output:
{2: 3, 3: 2, 4: 1}

25. List of Squares (List Comprehension)


lst = [x**2 for x in range(1, 6)]
print(lst)
Output:
[1, 4, 9, 16, 25]
26. Common Elements in Two Lists
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
common = []
for i in a:
if i in b:
[Link](i)
print("Common elements:", common)
Output:
Common elements: [3, 4]

27. Interchange First and Last Element


lst = [10, 20, 30, 40]
lst[0], lst[-1] = lst[-1], lst[0]
print(lst)
Output:
[40, 20, 30, 10]

28. Reverse a List Without Using Reverse()


lst = [1, 2, 3, 4]
rev = []
for i in lst[::-1]:
[Link](i)
print(rev)
Output:[4, 3, 2, 1]

29. Sum of Elements Without Using sum()


lst = [1, 2, 3, 4]
total = 0
for i in lst:
total += i
print("Sum:", total)
Output:Sum: 10

30. Find Prime Numbers in a List


lst = [2, 3, 4, 5, 6, 7, 8, 9]
prime = []
for n in lst:
if n > 1:
for i in range(2, n):
if n % i == 0:
break
else:
[Link](n)
print("Prime numbers:", prime)
Output:
Prime numbers: [2, 3, 5, 7]

You might also like