0% found this document useful (0 votes)
0 views7 pages

Python string programs

The document provides various Python code snippets demonstrating string manipulation techniques, including finding string length, reversing words, removing characters, and checking for vowels. It also covers methods for counting characters, removing duplicates, and identifying the least and most frequent characters in a string. Each section includes example code and explanations for different string operations.

Uploaded by

priyanka
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)
0 views7 pages

Python string programs

The document provides various Python code snippets demonstrating string manipulation techniques, including finding string length, reversing words, removing characters, and checking for vowels. It also covers methods for counting characters, removing duplicates, and identifying the least and most frequent characters in a string. Each section includes example code and explanations for different string operations.

Uploaded by

priyanka
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
You are on page 1/ 7

Find length of a string in python

# Python code to demonstrate string length

# using len

str = "geeks"

print(len(str))

Reverse words in a given String in Python

# Python code

# To reverse words in a given string

# input string

string = "geeks quiz practice code"

# reversing words in a given string

s = string.split()[::-1]

l = []

for i in s:

# appending reversed words to l

l.append(i)

# printing reverse words

print(" ".join(l))

Ways to remove i’th character from string in Python


# Initializing String
test_str = "GeeksForGeeks"

# Removing char at pos 3


# using replace
new_str = test_str.replace('e', '')

# Printing string after removal


# removes all occurrences of 'e'
print("The string after removal of i'th character( doesn't work) : " + new_str)

# Removing 1st occurrence of s, i.e 5th pos.


# if we wish to remove it.
new_str = test_str.replace('s', '', 1)

# Printing string after removal


# removes first occurrences of s
print("The string after removal of i'th character(works) : " + new_str)

Python – Avoid Spaces in string length


# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# Using isspace() + sum()

# initializing string
test_str = 'geeksforgeeks 33 is best'

# printing original string


print("The original string is : " + str(test_str))

# isspace() checks for space


# sum checks count
res = sum(not chr.isspace() for chr in test_str)

# printing result
print("The Characters Frequency avoiding spaces : " + str(res))
Python program to print even length words in a string
# Python code
# To print even length words in string

#input string
n="This is a python language"
#splitting the words in a given string
s=n.split(" ")
for i in s:
#checking the length of words
if len(i)%2==0:
print(i)

Python – Uppercase Half String


# Python3 code to demonstrate working of
# Uppercase Half String
# Using upper() + loop + len()

# initializing string
test_str = 'geeksforgeeks'

# printing original string


print("The original string is : " + str(test_str))

# computing half index


hlf_idx = len(test_str) // 2

res = ''
for idx in range(len(test_str)):
# uppercasing later half
if idx >= hlf_idx:
res += test_str[idx].upper()
else:
res += test_str[idx]

# printing result
print("The resultant string : " + str(res))

Python program to capitalize the first and last character of each word in a string
# Python program to capitalize
# first and last character of
# each word of a String

# Function to do the same


def word_both_cap(str):

# lambda function for capitalizing the


# first and last letter of words in
# the string
return ' '.join(map(lambda s: s[:-1]+s[-1].upper(),
s.title().split()))

# Driver's code
s = "welcome to geeksforgeeks"
print("String before:", s)
print("String after:", word_both_cap(str))

Python program to check if a string has at least one letter and one number
def checkString(str):

# initializing flag variable


flag_l = False
flag_n = False

# checking for letter and numbers in


# given string
for i in str:

# if string has letter


if i.isalpha():
flag_l = True

# if string has number


if i.isdigit():
flag_n = True

# returning and of flag


# for checking required condition
return flag_l and flag_n
# driver code
print(checkString('thishasboth29'))
print(checkString('geeksforgeeks'))

Python | Program to accept the strings which contains all vowels


# Python program to accept the strings
# which contains all the vowels

# Function for check if string


# is accepted or not
def check(string) :

string = string.lower()

# set() function convert "aeiou"


# string into set of characters
# i.e.vowels = {'a', 'e', 'i', 'o', 'u'}
vowels = set("aeiou")

# set() function convert empty


# dictionary into empty set
s = set({})

# looping through each


# character of the string
for char in string :

# Check for the character is present inside


# the vowels set or not. If present, then
# add into the set s by using add method
if char in vowels :
s.add(char)
else:
pass

# check the length of set s equal to length


# of vowels set or not. If equal, string is
# accepted otherwise not
if len(s) == len(vowels) :
print("Accepted")
else :
print("Not Accepted")

# Driver code
if __name__ == "__main__" :

string = "SEEquoiaL"

# calling function
check(string)
Python | Count the Number of matching characters in a pair of string
// C++ code to count number of matching
// characters in a pair of strings

# include <bits/stdc++.h>
using namespace std

// Function to count the matching characters


void count(string str1, string str2)
{
int c = 0, j = 0

// Traverse the string 1 char by char


for (int i=0
i < str1.length()
i++) {

// This will check if str1[i]


// is present in str2 or not
// str2.find(str1[i]) returns - 1 if not found
// otherwise it returns the starting occurrence
// index of that character in str2
if (str2.find(str1[i]) >= 0
and j == str1.find(str1[i]))
c += 1
j += 1
}
cout << "No. of matching characters are: "
<< c / 2
}

// Driver code
int main()
{
string str1 = "aabcddekll12@"
string str2 = "bb2211@55k"

count(str1, str2)
}
Python program to count number of vowels using sets in given string
string = "GeekforGeeks!"
vowels = "aeiouAEIOU"

count = sum(string.count(vowel) for vowel in vowels)


print(count)
Python Program to remove all duplicates from a given string
from collections import OrderedDict

# Function to remove all duplicates from string


# and order does not matter
def removeDupWithoutOrder(str):

# set() --> A Set is an unordered collection


# data type that is iterable, mutable,
# and has no duplicate elements.
# "".join() --> It joins two adjacent elements in
# iterable with any symbol defined in
# "" ( double quotes ) and returns a
# single string
return "".join(set(str))

# Function to remove all duplicates from string


# and keep the order of characters same
def removeDupWithOrder(str):
return "".join(OrderedDict.fromkeys(str))

# Driver program
if __name__ == "__main__":
str = "geeksforgeeks"
print ("Without Order = ",removeDupWithoutOrder(str))
print ("With Order = ",removeDupWithOrder(str))
Python – Least Frequent Character in String
# Python 3 code to demonstrate
# Least Frequent Character in String
# naive method

# initializing string
test_str = "GeeksforGeeks"

# printing original string


print ("The original string is : " + test_str)

# using naive method to get


# Least Frequent Character in String
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
res = min(all_freq, key = all_freq.get)

# printing result
print ("The minimum of all characters in GeeksforGeeks is : " + str(res))
Python | Maximum frequency character in String
# Python 3 code to demonstrate
# Maximum frequency character in String
# naive method

# initializing string
test_str = "GeeksforGeeks"

# printing original string


print ("The original string is : " + test_str)

# using naive method to get


# Maximum frequency character in String
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
res = max(all_freq, key = all_freq.get)

# printing result
print ("The maximum of all characters in GeeksforGeeks is : " + str(res))

You might also like