0% found this document useful (0 votes)
2 views

String

Uploaded by

hari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

String

Uploaded by

hari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

String

Write a program to print each character from the string along with its index.

s = input("Enter the String:")


index = 0

while index < len(s):


print("{} -> {}".format(s[index],index))
index = index+1

Program to print ASCII values of all characters.

def printAsciiValues(s):
for i in s:
asciiValue = ord(i)
print("{} -> {}".format(i,asciiValue))

s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
printAsciiValues(s)
print('-----')
s = 'abcdefghijklmnopqrstuvwxyz'
printAsciiValues(s)
print('-----')
s = '0123456789'
printAsciiValues(s)

Write a program to print how many CAPITAL letters and SMALL letters present
in string.

s = input("Enter the String:")


upperCase = 0
lowerCase = 0

for i in s:

String 1
if 'A'<=i<='Z':
upperCase = upperCase+1
elif 'a'<=i<='z':
lowerCase = lowerCase+1

print("Upper case characters in {} are {}".format(s,upperCase


print("Lower case characters in {} are {}".format(s,lowerCase

s = input("Enter the String:")


upperCase = 0
lowerCase = 0

for i in s:
asc = ord(i)
if 65<=asc<=90:
upperCase = upperCase+1
elif 97<=asc<=122:
lowerCase = lowerCase+1

print("Upper case characters in {} are {}".format(s,upperCase


print("Lower case characters in {} are {}".format(s,lowerCase

s = input("Enter the String:")


upperCase = 0
lowerCase = 0

for i in s:
if i.isupper():
upperCase = upperCase+1
elif i.islower():
lowerCase = lowerCase+1

print("Upper case characters in {} are {}".format(s,upperCase


print("Lower case characters in {} are {}".format(s,lowerCase

Write a program to print how many digits and special characters present in
string.

String 2
s = input("Enter the String:")

a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
b = '0123456789'

digitCount = 0
specialCount = 0

for i in s:
if i in b:
digitCount = digitCount+1
elif i not in a:
specialCount = specialCount+1

print("Digits present in {}:{}".format(s,digitCount))


print("Special Characters present in {}:{}".format(s,specialCo

s = input("Enter the String:")

digitCount = 0
specialCount = 0

for i in s:
if i.isdigit():
digitCount = digitCount+1
elif not i.isalnum():
specialCount = specialCount+1

print("Digits present in {}:{}".format(s,digitCount))


print("Special Characters present in {}:{}".format(s,specialCo

Write a program to reverse the string.

s = input("Enter the String:")

new=""

String 3
for i in range(len(s)-1,-1,-1):
new=new+s[i]

print(new)

s = input("Enter the String:")

print(s[::-1])

Define a method to return True if the given string is palindrome otherwise


return False.

def reverse(s):
return s[::-1]

def isPalindrome(s):
ns = ""

for i in s:
if 'A'<=i<='Z' :
i = chr(ord(i)+32)
ns = ns+i
elif i !=' ':
ns = ns+i

rev = reverse(ns)
return ns == rev

s = input("Enter the String:")

if isPalindrome(s):
print("Palindrome")
else:
print("Not a palindrome")

String 4
def isPalindrome(s):
s = s.replace(" ", "")
s = s.lower()
return s == s[::-1]

s = input("Enter the String:")

if isPalindrome(s):
print("Palindrome")
else:
print("Not a palindrome")

Write a program to convert all the characters in a string to Uppercase.

def to_uppercase(input_string):
result = ""
for char in input_string:
if 'a' <= char <= 'z':
uppercase_char = chr(ord(char) - 32)
result += uppercase_char
else:
result += char
return result

s = input("Enter the String:")


print(to_uppercase(s))

s = input("Enter the String:")


print(s.upper())

Write a program to print how many vowels and consonents present in string.

def getVowelConsoCount(s):

vowelCount = 0
consonantCount = 0

String 5
for char in s:
if ('a' <= char <= 'z') or ('A' <= char <= 'Z'):
if char in "aeiouAEIOU":
vowelCount += 1
else:
consonantCount += 1

return vowelCount,consonantCount

s = input("Enter the String:")


count = getVowelConsoCount(s)
print("Vowels -> {} and Consonents -> {}".format(count[0],co

Write a function to return the sum of digits present in the string.

def getSum(s):
sum = 0
for i in s:
if '0'<=i<='9':
i = int(i)
sum = sum+i
return sum

s = input("Enter the string:")


print(getSum(s))

Define a function to print the frequency of characters.

def getFrequency(s):
count = [0]*128

for i in s:
asc = ord(i)
count[asc] = count[asc]+1

for i in range(len(count)):
if count[i]!=0:

String 6
print("{} -> {}".format(chr(i),count[i]))

s = input("Enter the string:")


getFrequency(s)

Write a program to print how many characters each word has.

def getWordCount(s):
words = s.split()

for i in words:
print("{} -> {}".format(i,len(i)))

s = input("Enter the String:")


getWordCount(s)

def getWordCount(s):
w=""
s = s+" "
count = 0

for i in range(len(s)):
ch = s[i]
if ch==" ":
print("{} -> {}".format(w,count))
count=0
w=""
else:
w = w+ch
count=count+1

s = input("Enter the String:")


getWordCount(s)

Write a program to return highest length word from the string.

String 7
def getBiggestWord(s):
words = s.split()
big = 0
word = None
for i in words:
size = len(i)

if size>big:
big = size
word = i

return word

s = input("Enter the String:")


print(getBiggestWord(s))

def getBiggestWord(s):
bw = ""
w=""
s = s+" "

for i in range(len(s)):
ch = s[i]
if ch==" ":
if len(w) > len(bw):
bw = w
w=""
else:
w = w+ch
return bw

s = input("Enter the String:")


print(getBiggestWord(s))

Write a program to check weather the given string is PANAGRAM or Not


A

String 8
pangram is a sentence that contains every letter of the alphabet at least once.
Pangrams are often used in typography and testing fonts, as they provide a
comprehensive sample of the alphabet in a single phrase.
The quick brown fox jumps over a lazy dog

def isPanagram(st):
l = [0]*26

for char in st:


if 'A'<= char <='Z':
l[ord(char)-65] += 1
elif 'a' <= char <= 'z':
l[ord(char)-97] += 1

for i in l:
if i==0:
return False
return True

Write a program to check weather the given string is ANAGRAM or Not


An
anagram is a word or phrase formed by rearranging the letters of another word
or phrase, using all the original letters exactly once. To be an anagram, both
words or phrases must contain the same characters in the same quantity, just
arranged differently.

Listen → Silent

Elbow → Below

Triangle → Integral

def isAnagram(st1,st2):
count1 = getCount(st1)
count2 = getCount(st2)

for i in range(26):
if count1[i] != count2[i]:
return False
return True

String 9
def getCount(st):
l = [0]*26

for char in st:


if 'A'<= char <='Z':
l[ord(char)-65] += 1
elif 'a' <= char <= 'z':
l[ord(char)-97] += 1
return l

st1 = input("Enter String 1:")


st2 = input("Enter String 2:")

def isAnagram(st1,st2):
st1 = st1.replace(" ", "")
st2 = st2.replace(" ", "")

st1 = st1.lower()
st2 = st2.lower()

st1 = sorted(st1)
st2 = sorted(st2)

return st1==st2

st1 = input("Enter String 1:")


st2 = input("Enter String 2:")

print(isAnagram(st1, st2))

Write a program to convert the last character of each word to uppercase and
rest to lowercase.
Example: Hari Narayana Bhat N ⇒ harI narayanA bhaT N

String 10
⚠️ x = 0
if x != 0 and (10 / x) > 1: #This will raise error if evaluated.
print("This will not execute due to short-circuiting.")

def lastCaps(s):
ch = list(s)

for i in range(len(s)):
if i==len(s)-1 and ch[i] != ' ' or ch[i] != ' ' and c
if ch[i] >='a' and ch[i]<='z':
ch[i] = chr(ord(ch[i])-32)
else:
if ch[i] >='A' and ch[i] <='Z':
ch[i] = chr(ord(ch[i])+32)

ns=""
for i in ch:
ns = ns+i
return ns

s = input("Enter the String:")


print(lastCaps(s))

Write a function to swap every word first character with last character of same
word.
Hari Narayana ⇒ iarH aarayanN

def swapFwL(st):
ch = list(st)

f = 0
for i in range(len(ch)):
if i==0 and ch[i]!=" " or ch[i] !=" " and ch[i-1]=="
f = i;

String 11
elif i == len(ch)-1 and ch[i]!=" " or ch[i]!=" " and c
ch[f],ch[i] = ch[i],ch[f]

ns=""
for i in ch:
ns = ns+i
return ns

st = input("Enter the String: ")


print(swapFwL(st))

Write a function to change last character to lowercase and rest to uppercase.

Write a program to reverse the words in a sentence.


Rama and Sita ⇒ amaR dna atiS

def reverseWords(st):

rs = ""

i = 0
while i < len(ch):
rw = ""
# Reverse the current word
while i < len(ch) and ch[i] != " ":
rw = ch[i] + rw
i += 1
# Add the reversed word to the result
rs += rw
# Add a space if there's more to process
if i < len(ch) and ch[i] == " ":
rs += ch[i]
i += 1

return rs

String 12
st = input("Enter the String: ")
print(reverseWords(st))

Write a program to reverse the sentence.


example : Rama and Sita ⇒ Sita and Rama

def reverseSentence(st):
ch = list(st)
rs = ""

i=len(ch)-1
while i>=0:
l = i
while i >= 0 and ch[i] != " ":
i=i-1
f = i+1
while l>=f:
rs = rs+ch[f]
f=f+1
if i>=0:
rs = rs+ch[i]
i = i-1
return rs

st = input("Enter the String: ")


print(reverseSentence(st))

String 13

You might also like