String methods Programs
Python program to check if a string is palindrome or not
s = input("Enter Name")
k=s[::-1]
if s==k:
print("Palindrome")
else:
print("Not Palindrome")
Python program to check whether the string is Symmetrical or Palindrome
def symmetry(a):
n = len(a)
flag = 0
# Check if the string's length
# is odd or even
if n%2:
mid = n//2 +1
else:
mid = n//2
start1 = 0
start2 = mid
while(start1 < mid and start2 < n):
if (a[start1]== a[start2]):
start1 = start1 + 1
start2 = start2 + 1
else:
flag = 1
break
if flag == 0:
print("The entered string is symmetrical")
else:
print("The entered string is not symmetrical")
string = 'amaama'
symmetry(string)
output
Input: khokho
Output:
The entered string is symmetrical
Input:amaama
Output:
The entered string is symmetrical
Reverse words in a given String in Python
# Function to reverse words of string
def rev_sentence(sentence):
# first split the string into words
words = sentence.split(' ')
# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))
# finally return the joined string
return reverse_sentence
input = input("Enter Sentence")
print (rev_sentence(input))
Output:
Enter Sentencevision compuer is one of the famous
famous the of one is compuer vision
Ways to remove i’th character from string in Python
Method 1:
test_str =input("Ennter sentence")
print ("The original string is : " + test_str)
new_str = test_str.replace('s', '', 1)
print ("The string after removal of i'th character(works) : " + new_str)
Python | Check if a Substring is Present in a Given String
Method1:
# function to check if small string is
# there in big string
def check(string, sub_str):
if (string.find(sub_str) == -1):
print("NO")
else:
print("YES")
# driver code
string = "geeks for geeks"
sub_str ="geek"
check(string, sub_str)
Method2
def check(s2, s1):
if (s2.count(s1)>0):
print("YES")
else:
print("NO")
s2 = "A geek in need is a geek indeed"
s1 ="geek"
check(s2, s1)
Python – Words Frequency in String Shorthands
Method1:
# Python code to demonstrate
# method to remove i'th character
# using join() + list comprehension
# Initializing String
test_str = "GeeksForGeeks"
# Printing original string
print ("The original string is : " + test_str)
# Removing char at pos 3
# using join() + list comprehension
new_str = ''.join([test_str[i] for i in range(len(test_str)) if i != 2])
# Printing string after removal
# removes ele. at 3rd index
print ("The string after removal of i'th character : " + new_str)
method2:
# Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using Counter() + split()
from collections import Counter
# initializing string
test_str = 'Gfg is best . Geeks are good and Geeks like Gfg'
# printing original string
print("The original string is : " + str(test_str))
# Words Frequency in String Shorthands
# Using Counter() + split()
res = Counter(test_str.split())
# printing result
print("The words frequency : " + str(dict(res)))
output:
The original string is : Gfg is best . Geeks are good and Geeks like Gfg
The words frequency : {‘Gfg’: 2, ‘is’: 1, ‘best’: 1, ‘.’: 1, ‘Geeks’: 2, ‘are’: 1, ‘good’: 1, ‘and’: 1, ‘like’: 1}
Python program to print even length words in a string
# Python3 program to print
# even length words in a string
def printWords(s):
# split the string
s = s.split(' ')
# iterate in words of string
for word in s:
# if length is even
if len(word)%2==0:
print(word)
# Driver Code
s = "i am muskan"
printWords(s)
Python program to accept the strings which contains all vowels
# Python program for the above approach
def check(string):
if len(set(string.lower()).intersection("aeiou")) >= 5:
return ('accepted')
else:
return ("not accepted")
# Driver code
if __name__ == "__main__":
string = "geeksforgeeks"
print(check(string))
method2:
def check(string):
string = string.replace(' ', '')
string = string.lower()
vowel = [string.count('a'), string.count('e'), string.count(
'i'), string.count('o'), string.count('u')]
# If 0 is present int vowel count array
if vowel.count(0) > 0:
return('not accepted')
else:
return('accepted')
# Driver code
if __name__ == "__main__":
string = "SEEquoiaL"
print(check(string))
Count the Number of matching characters in a pair of string
# Count the Number of matching characters in
# a pair of string
import re
ip1 = "geeks"
ip2 = "geeksonly"
c = 0
for i in ip1:
if re.search(i,ip2):
c=c+1
print("No. of matching characters are ", c)
method2:
# Python code to count number of matching
# characters in a pair of strings
# count function
def count(str1, str2):
c, j = 0, 0
# loop executes till length of str1 and
# stores value of str1 character by character
# and stores in i at each iteration.
for i in str1:
# this will check if character extracted from
# str1 is present in str2 or not(str2.find(i)
# return -1 if not found otherwise return the
# starting occurrence index of that character
# in str2) and j == str1.find(i) is used to
# avoid the counting of the duplicate characters
# present in str1 found in str2
if str2.find(i)>= 0 and j == str1.find(i):
c += 1
j += 1
print ('No. of matching characters are : ', c)
# Main function
def main():
str1 ='aabcddekll12@' # first string
str2 ='bb2211@55k' # second string
count(str1, str2) # calling count function
# Driver Code
if __name__=="__main__":
main()
Remove all duplicates from a given string in Python
def removeDuplicate(str):
s=set(str)
s="".join(s)
print("Without Order:",s)
t=""
for i in str:
if(i in t):
pass
else:
t=t+i
print("With Order:",t)
str="geeksforgeeks"
removeDuplicate(str)
method2:
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))
Maximum frequency character in String
# Python 3 code to demonstrate
# Maximum frequency character in String
# collections.Counter() + max()
from collections import Counter
# initializing string
test_str = "GeeksforGeeks"
# printing original string
print ("The original string is : " + test_str)
# using collections.Counter() + max() to get
# Maximum frequency character in String
res = Counter(test_str)
res = max(res, key = res.get)
# printing result
print ("The maximum of all characters in GeeksforGeeks is : " + str(res))
Program to check if a string contains any special character
# Python3 program to check if a string
# contains any special character
# import required package
import re
# Function checks if the string
# contains any special character
def run(string):
# Make own character set and pass
# this as argument in compile method
regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
# Pass the string in search
# method of regex object.
if(regex.search(string) == None):
print("String is accepted")
else:
print("String is not accepted.")
# Driver Code
if __name__ == '__main__' :
# Enter the string
string = "Geeks$For$Geeks"
# calling run function
run(string)
output
Input : Geeks$For$Geeks
Output : String is not accepted.
Input : Geeks For Geeks
Output : String is accepted
Find words which are greater than given length k
A string is given, and you have to find all the words (substrings separated by a space) which are greater than the given length k.
# Python program to find all string
# which are greater than given length k
# function find sttring greater than length k
def string_k(k, str):
# create the empty string
string = []
# split the string where space is comes
text = str.split(" ")
# iterate the loop till every substring
for x in text:
# if length of current sub string
# is greater than k then
if len(x) > k:
# append this sub string in
# string list
string.append(x)
# return string list
return string
# Driver Program
k = 3
str ="geek for geeks"
print(string_k(k, str))
output:
Input : str = "hello geeks for geeks
is computer science portal"
k = 4
Output : hello geeks geeks computer
science portal
Explanation : The output is list of all
words that are of length more than k.
Python program to split and join a string
# Python program to split a string and
# join it using different delimiter
def split_string(string):
# Split the string based on space delimiter
list_string = string.split(' ')
return list_string
def join_string(list_string):
# Join the string based on '-' delimiter
string = '-'.join(list_string)
return string
# Driver Function
if __name__ == '__main__':
string = 'Geeks for Geeks'
# Splitting a string
list_string = split_string(string)
print(list_string)
# Join list of strings into one
new_string = join_string(list_string)
print(new_string)
output:
Split the string into list of strings
Input : Geeks for Geeks
Output : ['Geeks', 'for', 'Geeks']
Python | Check if a given string is binary string or not
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check2(string) :
# initialize the variable t
# with '01' string
t = '01'
# initialize the variable count
# with 0 value
count = 0
# looping through each character
# of the string .
for char in string :
# check the character is present in
# string t or not.
# if this condition is true
# assign 1 to the count variable
# and break out of the for loop
# otherwise pass
if char not in t :
count = 1
break
else :
pass
# after coming out of the loop
# check value of count is non-zero or not
# if the value is non-zero the en condition is true
# and string is not accepted
# otherwise string is accepted
if count :
print("No")
else :
print("Yes")
# driver code
if __name__ == "__main__" :
string = "001021010001010"
# function calling
check2(string)
output:
Input: str = "01010101010"
Output: Yes
Input: str = "geeks101"
Output: No
Python program to find uncommon words from two Strings
# Python3 program to find a list of uncommon words
# Function to return all uncommon words
def UncommonWords(A, B):
# count will contain all the word counts
count = {}
# insert words of string A to hash
for word in A.split():
count[word] = count.get(word, 0) + 1
# insert words of string B to hash
for word in B.split():
count[word] = count.get(word, 0) + 1
# return required list of words
return [word for word in count if count[word] == 1]
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B))
method2
def uncommon(a,b):
a=a.split()
b=b.split()
k=set(a).symmetric_difference(set(b))
return k
#Driver code
if __name__=="__main__":
a="apple banana mango"
b="banana fruits mango"
print(list(uncommon(a,b)))
Python – Replace duplicate Occurrence in String
# Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. \
Classes help understand better . '
# printing original string
print("The original string is : " + str(test_str))
# initializing replace mapping
repl_dict = {'Gfg' : 'It', 'Classes' : 'They' }
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
test_list = test_str.split(' ')
res = set()
for idx, ele in enumerate(test_list):
if ele in repl_dict:
if ele in res:
test_list[idx] = repl_dict[ele]
else:
res.add(ele)
res = ' '.join(test_list)
# printing result
print("The string after replacing : " + str(res))
Replace multiple words with K
# Python3 code to demonstrate working of
# Replace multiple words with K
# Using join() + split() + list comprehension
# initializing string
test_str = 'Geeksforgeeks is best for geeks and CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing word list
word_list = ["best", 'CS', 'for']
# initializing replace word
repl_wrd = 'gfg'
# Replace multiple words with K
# Using join() + split() + list comprehension
res = ' '.join([repl_wrd if idx in word_list else idx for idx in test_str.split()])
# printing result
print("String after multiple replace : " + str(res))
method2:
# Python3 code to demonstrate working of
# Replace multiple words with K
# Using regex + join()
import re
# initializing string
test_str = 'Geeksforgeeks is best for geeks and CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing word list
word_list = ["best", 'CS', 'for']
# initializing replace word
repl_wrd = 'gfg'
# Replace multiple words with K
# Using regex + join()
res = re.sub("|".join(sorted(word_list, key = len, reverse = True)), repl_wrd, test_str)
# printing result
print("String after multiple replace : " + str(res))
Python | Permutation of a given string using inbuilt function
# Function to find permutations of a given string
from itertools import permutations
def allPermutations(str):
# Get all permutations of string 'ABC'
permList = permutations(str)
# print all permutations
for perm in list(permList):
print (''.join(perm))
# Driver program
if __name__ == "__main__":
str = 'ABC'
allPermutations(str)
method2:
Permutations of a given string with repeating characters
The idea is to use dictionary to avoid printing duplicates.
from itertools import permutations
import string
s = "GEEK"
a = string.ascii_letters
p = permutations(s)
# Create a dictionary
d = []
for i in list(p):
# Print only if not in dictionary
if (i not in d):
d.append(i)
print(''.join(i))
Check for URL in a String
# Python code to find the URL from an input string
# Using the regular expression
import re
def Find(string):
# findall() has been used
# with valid conditions for urls in string
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
url = re.findall(regex,string)
return [x[0] for x in url]
# Driver Code
string = 'My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of http://www.geeksforgeeks.org/'
print("Urls: ", Find(string))
Execute a String of Code in Python
# Python program to illustrate use of exec to
# execute a given code as string.
# function illustrating how exec() functions.
def exec_code():
LOC = """
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
"""
exec(LOC)
# Driver Code
exec_code()
output
Input:
code = """ a = 6+5
print(a)"""
Output:
11
Explanation:
Mind it that "code" is a variable and
not python code. It contains another code,
which we need to execute.
Input:
code = """ def factorial(num):
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))"""
Output:
120
Explanation:
On executing the program cantaining the
variable in Python we must get the result
after executing the content of the variable.
Find all duplicate characters in string
from collections import Counter
def find_dup_char(input):
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
WC = Counter(input)
j = -1
# Finding no. of occurrence of a character
# and get the index of it.
for i in WC.values():
j = j + 1
if( i > 1 ):
print WC.keys()[j],
# Driver program
if __name__ == "__main__":
input = 'geeksforgeeks'
find_dup_char(input)
Replace all occurrences of a substring in a string
# Python3 code to demonstrate working of
# Swap Binary substring
# Using translate()
# initializing string
test_str = "geeksforgeeks"
# printing original string
print("The original string is : " + test_str)
# Swap Binary substring
# Using translate()
temp = str.maketrans("geek", "abcd")
test_str = test_str.translate(temp)
# printing result
print("The string after swap : " + str(test_str))
Extract date in String
# Python3 code to demonstrate working of
# Detect date in String
# Using re.search() + strptime()
import re
from datetime import datetime
# initializing string
test_str = "gfg at 2021-01-04"
# printing original string
print("The original string is : " + str(test_str))
# searching string
match_str = re.search(r'\d{4}-\d{2}-\d{2}', test_str)
# computed date
# feeding format
res = datetime.strptime(match_str.group(), '%Y-%m-%d').date()
# printing result
print("Computed date : " + str(res))
method2:
# Python3 code to demonstrate working of
# Detect date in String
# Using python-dateutil()
from dateutil import parser
# initializing string
test_str = "gfg at 2021-01-04"
# printing original string
print("The original string is : " + str(test_str))
# extracting date using inbuilt func.
res = parser.parse(test_str, fuzzy=True)
# printing result
print("Computed date : " + str(res)[:10])
Python program to extract numeric suffix from string
# Python3 code to demonstrate working of
# Extract Suffix numbers
# Using loop + isdigit() + slicing
# initializing string
test_str = "GFG04"
# printing original string
print("The original string is : " + str(test_str))
# loop for fetching the 1st non digit index
rev_str = test_str[::-1]
temp_idx = 0
for idx, ele in enumerate(rev_str):
if not ele.isdigit():
temp_idx = idx
break
# reversing the extracted string to
# get number
res = rev_str[:temp_idx][::-1]
# printing result
print("Suffix number : " + str(res))
Get Last N characters of a string
# get input
Str = "Geeks For Geeks!"
N = 4
# print the string
print(Str)
# iterate loop
while(N > 0):
# print character
print(Str[-N], end='')
# decrement the value of N
N = N-1
Method2:
# get input
Str = "Geeks For Geeks!"
N = 4
# print the string
print(Str)
# get length of string
length = len(Str)
# create a new string of last N characters
Str2 = Str[length - N:]
# print Last N characters
print(Str2)
Find all the strings that are substrings to the given list of strings
# Python3 code to demonstrate working of
# Substring Intersections
# Using list comprehension
# initializing lists
test_list1 = ["Geeksforgeeks", "best", "for", "geeks"]
test_list2 = ["Geeks", "win", "or", "learn"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# using list comprehension for nested loops
res = list(
set([ele1 for sub1 in test_list1 for ele1 in test_list2 if ele1 in sub1]))
# printing result
print("Substrings Intersections : " + str(res))
Print the last word in a sentence
# Function which returns last word
def lastWord(string):
# taking empty string
newstring = ""
# calculating length of string
length = len(string)
# traversing from last
for i in range(length-1, 0, -1):
# if space is occured then return
if(string[i] == " "):
# return reverse of newstring
return newstring[::-1]
else:
newstring = newstring + string[i]
# Driver code
string = "Learn algorithms at geeksforgeeks"
print(lastWord(string))
Approach #2
# Function which returns last word
def lastWord(string):
# split by space and converting
# string to list and
lis = list(string.split(" "))
# length of list
length = len(lis)
# returning last element in list
return lis[length-1]
# Driver code
string = "Learn algorithms at geeksforgeeks"
print(lastWord(string))
For
More Explanation
&
Online Classes
More Explanation
&
Online Classes
Contact Us:
+919885348743
+919885348743