Description
stringlengths 9
105
| Link
stringlengths 45
135
| Code
stringlengths 10
26.8k
| Test_Case
stringlengths 9
202
| Merge
stringlengths 63
27k
|
---|---|---|---|---|
Python program to find the character position of Kth word from a list of strings | https://www.geeksforgeeks.org/python-program-to-find-the-character-position-of-kth-word-from-a-list-of-strings/ | # Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using next() + zip() + count()
from itertools import count
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# count() for getting count
# pairing using zip()
cnt = count()
res = next(j for sub in test_list for j, idx in zip(range(len(sub)), cnt) if idx == K)
# printing result
print("Index of character at Kth position word : " + str(res)) |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python program to find the character position of Kth word from a list of strings
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using next() + zip() + count()
from itertools import count
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# count() for getting count
# pairing using zip()
cnt = count()
res = next(j for sub in test_list for j, idx in zip(range(len(sub)), cnt) if idx == K)
# printing result
print("Index of character at Kth position word : " + str(res))
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |
Python program to find the character position of Kth word from a list of strings | https://www.geeksforgeeks.org/python-program-to-find-the-character-position-of-kth-word-from-a-list-of-strings/ | # Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using nested loop
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# initializing index counter
idx = 0
# iterating over each word in the list
for word in test_list:
# if the kth position is in the current word
if idx + len(word) > K:
# printing result
print("Index of character at Kth position word : " + str(K - idx))
break
# if the kth position is not in the current word
else:
idx += len(word)
# if the kth position is beyond the end of the list
else:
print("K is beyond the end of the list") |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python program to find the character position of Kth word from a list of strings
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using nested loop
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# initializing index counter
idx = 0
# iterating over each word in the list
for word in test_list:
# if the kth position is in the current word
if idx + len(word) > K:
# printing result
print("Index of character at Kth position word : " + str(K - idx))
break
# if the kth position is not in the current word
else:
idx += len(word)
# if the kth position is beyond the end of the list
else:
print("K is beyond the end of the list")
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |
Python - Right and Left Shift characters in String | https://www.geeksforgeeks.org/python-right-and-left-shift-characters-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using String multiplication + string slicing
# Initializing string
test_str = "geeksforgeeks"
# Printing original string
print("The original string is : " + test_str)
# Initializing right rot
r_rot = 7
# Initializing left rot
l_rot = 3
# Right and Left Shift characters in String
# Using String multiplication + string slicing
res = (test_str * 3)[len(test_str) + r_rot - l_rot : 2 * len(test_str) + r_rot - l_rot]
# Printing result
print("The string after rotation is : " + str(res)) |
#Output : The original string is : geeksforgeeks | Python - Right and Left Shift characters in String
# Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using String multiplication + string slicing
# Initializing string
test_str = "geeksforgeeks"
# Printing original string
print("The original string is : " + test_str)
# Initializing right rot
r_rot = 7
# Initializing left rot
l_rot = 3
# Right and Left Shift characters in String
# Using String multiplication + string slicing
res = (test_str * 3)[len(test_str) + r_rot - l_rot : 2 * len(test_str) + r_rot - l_rot]
# Printing result
print("The string after rotation is : " + str(res))
#Output : The original string is : geeksforgeeks
[END] |
Python - Right and Left Shift characters in String | https://www.geeksforgeeks.org/python-right-and-left-shift-characters-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using % operator and string slicing
# Initializing string
test_str = "geeksforgeeks"
# Printing original string
print("The original string is : " + test_str)
# Initializing right rot
r_rot = 7
# Initializing left rot
l_rot = 3
# Right and Left Shift characters in String
# Using % operator and string slicing
temp = (r_rot - l_rot) % len(test_str)
res = test_str[temp:] + test_str[:temp]
# Printing result
print("The string after rotation is : " + str(res)) |
#Output : The original string is : geeksforgeeks | Python - Right and Left Shift characters in String
# Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using % operator and string slicing
# Initializing string
test_str = "geeksforgeeks"
# Printing original string
print("The original string is : " + test_str)
# Initializing right rot
r_rot = 7
# Initializing left rot
l_rot = 3
# Right and Left Shift characters in String
# Using % operator and string slicing
temp = (r_rot - l_rot) % len(test_str)
res = test_str[temp:] + test_str[:temp]
# Printing result
print("The string after rotation is : " + str(res))
#Output : The original string is : geeksforgeeks
[END] |
Python - Right and Left Shift characters in String | https://www.geeksforgeeks.org/python-right-and-left-shift-characters-in-string/?ref=leftbar-rightbar | def left_shift_string(string, n):
char_list = list(string)
rotated_list = char_list[n:] + char_list[:n]
rotated_string = "".join(rotated_list)
return rotated_string
def right_shift_string(string, n):
char_list = list(string)
rotated_list = char_list[-n:] + char_list[:-n]
rotated_string = "".join(rotated_list)
return rotated_string
string = "geeksforgeeks"
n = 3
left_rotated_string = left_shift_string(string, n)
right_rotated_string = right_shift_string(string, n)
print("Original string:", string)
print("Left rotated string:", left_rotated_string)
print("Right rotated string:", right_rotated_string) |
#Output : The original string is : geeksforgeeks | Python - Right and Left Shift characters in String
def left_shift_string(string, n):
char_list = list(string)
rotated_list = char_list[n:] + char_list[:n]
rotated_string = "".join(rotated_list)
return rotated_string
def right_shift_string(string, n):
char_list = list(string)
rotated_list = char_list[-n:] + char_list[:-n]
rotated_string = "".join(rotated_list)
return rotated_string
string = "geeksforgeeks"
n = 3
left_rotated_string = left_shift_string(string, n)
right_rotated_string = right_shift_string(string, n)
print("Original string:", string)
print("Left rotated string:", left_rotated_string)
print("Right rotated string:", right_rotated_string)
#Output : The original string is : geeksforgeeks
[END] |
Python - Right and Left Shift characters in String | https://www.geeksforgeeks.org/python-right-and-left-shift-characters-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using String multiplication + string slicing
# Initializing string
test_str = "geeksforgeeks"
# Printing original string
print("The original string is : " + test_str)
# Initializing right rot
r_rot = 7
# Initializing left rot
l_rot = 3
# Rotating string
# using lambda function
rotate = lambda s: (s * 3)[len(s) + r_rot - l_rot : 2 * len(s) + r_rot - l_rot]
# Right and Left Shift characters in String
# Using String multiplication + string slicing
res = rotate(test_str)
# Printing result
print("The string after rotation is : " + str(res)) |
#Output : The original string is : geeksforgeeks | Python - Right and Left Shift characters in String
# Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using String multiplication + string slicing
# Initializing string
test_str = "geeksforgeeks"
# Printing original string
print("The original string is : " + test_str)
# Initializing right rot
r_rot = 7
# Initializing left rot
l_rot = 3
# Rotating string
# using lambda function
rotate = lambda s: (s * 3)[len(s) + r_rot - l_rot : 2 * len(s) + r_rot - l_rot]
# Right and Left Shift characters in String
# Using String multiplication + string slicing
res = rotate(test_str)
# Printing result
print("The string after rotation is : " + str(res))
#Output : The original string is : geeksforgeeks
[END] |
Python - Right and Left Shift characters in String | https://www.geeksforgeeks.org/python-right-and-left-shift-characters-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using list comprehension and string concatenation
# Initializing string
test_str = "geeksforgeeks"
# Printing original string
print("The original string is : " + test_str)
# Initializing right rot
r_rot = 7
# Initializing left rot
l_rot = 3
# Using list comprehension and string concatenation
res = "".join(
[test_str[(i + r_rot - l_rot) % len(test_str)] for i in range(len(test_str))]
)
# Printing result
print("The string after rotation is : " + res) |
#Output : The original string is : geeksforgeeks | Python - Right and Left Shift characters in String
# Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using list comprehension and string concatenation
# Initializing string
test_str = "geeksforgeeks"
# Printing original string
print("The original string is : " + test_str)
# Initializing right rot
r_rot = 7
# Initializing left rot
l_rot = 3
# Using list comprehension and string concatenation
res = "".join(
[test_str[(i + r_rot - l_rot) % len(test_str)] for i in range(len(test_str))]
)
# Printing result
print("The string after rotation is : " + res)
#Output : The original string is : geeksforgeeks
[END] |
Python | Exceptional Split in String | https://www.geeksforgeeks.org/python-exceptional-split-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Exceptional Split in String
# Using loop + split()
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using loop + split()
temp = ""
res = []
check = 0
for ele in test_str:
if ele == "(":
check += 1
elif ele == ")":
check -= 1
if ele == ", " and check == 0:
if temp.strip():
res.append(temp)
temp = ""
else:
temp += ele
if temp.strip():
res.append(temp)
# printing result
print("The string after exceptional split : " + str(res)) |
#Output : The original string is : gfg, is, (best, for), geeks | Python | Exceptional Split in String
# Python3 code to demonstrate working of
# Exceptional Split in String
# Using loop + split()
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using loop + split()
temp = ""
res = []
check = 0
for ele in test_str:
if ele == "(":
check += 1
elif ele == ")":
check -= 1
if ele == ", " and check == 0:
if temp.strip():
res.append(temp)
temp = ""
else:
temp += ele
if temp.strip():
res.append(temp)
# printing result
print("The string after exceptional split : " + str(res))
#Output : The original string is : gfg, is, (best, for), geeks
[END] |
Python | Exceptional Split in String | https://www.geeksforgeeks.org/python-exceptional-split-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Exceptional Split in String
# Using regex()
import re
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using regex()
res = re.split(r", (?!\S\)|\()", test_str)
# printing result
print("The string after exceptional split : " + str(res)) |
#Output : The original string is : gfg, is, (best, for), geeks | Python | Exceptional Split in String
# Python3 code to demonstrate working of
# Exceptional Split in String
# Using regex()
import re
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using regex()
res = re.split(r", (?!\S\)|\()", test_str)
# printing result
print("The string after exceptional split : " + str(res))
#Output : The original string is : gfg, is, (best, for), geeks
[END] |
Python | Exceptional Split in String | https://www.geeksforgeeks.org/python-exceptional-split-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Exceptional Split in String
# Using str.split() and list comprehension
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using str.split() and list comprehension
patterns = [", ", ", ("]
split_str = test_str.split(", ")
res_list = [split_str[0]]
for i in range(1, len(split_str)):
if any(split_str[i - 1].endswith(p) for p in patterns):
res_list[-1] += ", " + split_str[i]
else:
res_list.append(split_str[i])
# printing result
print("The string after exceptional split : " + str(res_list)) |
#Output : The original string is : gfg, is, (best, for), geeks | Python | Exceptional Split in String
# Python3 code to demonstrate working of
# Exceptional Split in String
# Using str.split() and list comprehension
# initializing string
test_str = "gfg, is, (best, for), geeks"
# printing original string
print("The original string is : " + test_str)
# Exceptional Split in String
# Using str.split() and list comprehension
patterns = [", ", ", ("]
split_str = test_str.split(", ")
res_list = [split_str[0]]
for i in range(1, len(split_str)):
if any(split_str[i - 1].endswith(p) for p in patterns):
res_list[-1] += ", " + split_str[i]
else:
res_list.append(split_str[i])
# printing result
print("The string after exceptional split : " + str(res_list))
#Output : The original string is : gfg, is, (best, for), geeks
[END] |
Python - Split String on Vowels | https://www.geeksforgeeks.org/python-split-string-on-vowels/ | def split_on_vowels(test_str):
vowels = "aeiouAEIOU"
result = []
temp = ""
for char in test_str:
if char in vowels:
if temp != "":
result.append(temp)
temp = ""
else:
temp += char
if temp != "":
result.append(temp)
return result
test_str = "GFGaBstuforigeeks"
print(split_on_vowels(test_str)) |
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks'] | Python - Split String on Vowels
def split_on_vowels(test_str):
vowels = "aeiouAEIOU"
result = []
temp = ""
for char in test_str:
if char in vowels:
if temp != "":
result.append(temp)
temp = ""
else:
temp += char
if temp != "":
result.append(temp)
return result
test_str = "GFGaBstuforigeeks"
print(split_on_vowels(test_str))
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']
[END] |
Python - Split String on Vowels | https://www.geeksforgeeks.org/python-split-string-on-vowels/ | # Python3 code to demonstrate working of
# Split String on vowels
# Using split() + regex
import re
# initializing strings
test_str = "GFGaBste4oCS"
# printing original string
print("The original string is : " + str(test_str))
# splitting on vowels
# constructing vowels list
# and separating using | operator
res = re.split("a|e|i|o|u", test_str)
# printing result
print("The splitted string : " + str(res)) |
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks'] | Python - Split String on Vowels
# Python3 code to demonstrate working of
# Split String on vowels
# Using split() + regex
import re
# initializing strings
test_str = "GFGaBste4oCS"
# printing original string
print("The original string is : " + str(test_str))
# splitting on vowels
# constructing vowels list
# and separating using | operator
res = re.split("a|e|i|o|u", test_str)
# printing result
print("The splitted string : " + str(res))
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']
[END] |
Python - Split String on Vowels | https://www.geeksforgeeks.org/python-split-string-on-vowels/ | # Python3 code to demonstrate working of
# Split String on vowels
# initializing strings
test_str = "GFGaBste4oCS"
# printing original string
print("The original string is : " + str(test_str))
# splitting on vowels
vow = "aeiouAEIOU"
for i in test_str:
if i in vow:
test_str = test_str.replace(i, "*")
res = test_str.split("*")
# printing result
print("The splitted string : " + str(res)) |
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks'] | Python - Split String on Vowels
# Python3 code to demonstrate working of
# Split String on vowels
# initializing strings
test_str = "GFGaBste4oCS"
# printing original string
print("The original string is : " + str(test_str))
# splitting on vowels
vow = "aeiouAEIOU"
for i in test_str:
if i in vow:
test_str = test_str.replace(i, "*")
res = test_str.split("*")
# printing result
print("The splitted string : " + str(res))
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']
[END] |
Python - Split String on Vowels | https://www.geeksforgeeks.org/python-split-string-on-vowels/ | # Python3 code to demonstrate working of
# Split String on vowels
# initializing strings
test_str = "GFGaBste4oCS"
# printing original string
print("The original string is : " + str(test_str))
# splitting on vowels
x = [97, 101, 105, 111, 117, 65, 69, 73, 79, 85]
for i in test_str:
if ord(i) in x:
test_str = test_str.replace(i, "*")
res = test_str.split("*")
# printing result
print("The splitted string : " + str(res)) |
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks'] | Python - Split String on Vowels
# Python3 code to demonstrate working of
# Split String on vowels
# initializing strings
test_str = "GFGaBste4oCS"
# printing original string
print("The original string is : " + str(test_str))
# splitting on vowels
x = [97, 101, 105, 111, 117, 65, 69, 73, 79, 85]
for i in test_str:
if ord(i) in x:
test_str = test_str.replace(i, "*")
res = test_str.split("*")
# printing result
print("The splitted string : " + str(res))
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']
[END] |
Python - Split String on Vowels | https://www.geeksforgeeks.org/python-split-string-on-vowels/ | import operator as op
def split_on_vowels(test_str):
vowels = "aeiouAEIOU"
result = []
temp = ""
for char in test_str:
if op.countOf(vowels, char) > 0:
if temp != "":
result.append(temp)
temp = ""
else:
temp += char
if temp != "":
result.append(temp)
return result
test_str = "GFGaBstuforigeeks"
print(split_on_vowels(test_str)) |
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks'] | Python - Split String on Vowels
import operator as op
def split_on_vowels(test_str):
vowels = "aeiouAEIOU"
result = []
temp = ""
for char in test_str:
if op.countOf(vowels, char) > 0:
if temp != "":
result.append(temp)
temp = ""
else:
temp += char
if temp != "":
result.append(temp)
return result
test_str = "GFGaBstuforigeeks"
print(split_on_vowels(test_str))
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']
[END] |
Python - Split String on Vowels | https://www.geeksforgeeks.org/python-split-string-on-vowels/ | import itertools
# Define the string to be split
test_str = "GFGaBste4oCS"
# Define the vowels to split the string on
vowels = "aeiouAEIOU"
# Print the original string
print("The original string is:", test_str)
# Use itertools.groupby to group adjacent characters in test_str based on if they are in vowels
res = [
list(g) for k, g in itertools.groupby(test_str, key=lambda x: x not in vowels) if k
]
# Join each group of characters into a string
res = ["".join(substring) for substring in res]
# Print the final split string
print("The split string is:", res)
# this code is contributed by Asif_shaik |
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks'] | Python - Split String on Vowels
import itertools
# Define the string to be split
test_str = "GFGaBste4oCS"
# Define the vowels to split the string on
vowels = "aeiouAEIOU"
# Print the original string
print("The original string is:", test_str)
# Use itertools.groupby to group adjacent characters in test_str based on if they are in vowels
res = [
list(g) for k, g in itertools.groupby(test_str, key=lambda x: x not in vowels) if k
]
# Join each group of characters into a string
res = ["".join(substring) for substring in res]
# Print the final split string
print("The split string is:", res)
# this code is contributed by Asif_shaik
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']
[END] |
Python - Split String on Vowels | https://www.geeksforgeeks.org/python-split-string-on-vowels/ | # initializing string
test_str = "GFGaBste4oCS"
# create a translation table that replaces vowels with spaces
trans_table = str.maketrans("aeiouAEIOU", " " * 10)
# split the string on spaces
res = test_str.translate(trans_table).split()
# printing result
print("The splitted string : " + str(res))
# This code is contributed by Vinay Pinjala. |
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks'] | Python - Split String on Vowels
# initializing string
test_str = "GFGaBste4oCS"
# create a translation table that replaces vowels with spaces
trans_table = str.maketrans("aeiouAEIOU", " " * 10)
# split the string on spaces
res = test_str.translate(trans_table).split()
# printing result
print("The splitted string : " + str(res))
# This code is contributed by Vinay Pinjala.
#Output : ['GFG', 'Bst', 'f', 'r', 'g', 'ks']
[END] |
Python - Mirror Image of String | https://www.geeksforgeeks.org/python-mirror-image-of-string/ | # Python3 code to demonstrate working of
# Mirror Image of String
# Using Mirror Image of String
# initializing strings
test_str = "void"
# printing original string
print("The original string is : " + str(test_str))
# initializing mirror dictionary
mir_dict = {"b": "d", "d": "b", "i": "i", "o": "o", "v": "v", "w": "w", "x": "x"}
res = ""
# accessing letters from dictionary
for ele in test_str:
if ele in mir_dict:
res += mir_dict[ele]
# if any character not present, flagging to be invalid
else:
res = "Not Possible"
break
# printing result
print("The mirror string : " + str(res)) |
#Output : The original string is : void | Python - Mirror Image of String
# Python3 code to demonstrate working of
# Mirror Image of String
# Using Mirror Image of String
# initializing strings
test_str = "void"
# printing original string
print("The original string is : " + str(test_str))
# initializing mirror dictionary
mir_dict = {"b": "d", "d": "b", "i": "i", "o": "o", "v": "v", "w": "w", "x": "x"}
res = ""
# accessing letters from dictionary
for ele in test_str:
if ele in mir_dict:
res += mir_dict[ele]
# if any character not present, flagging to be invalid
else:
res = "Not Possible"
break
# printing result
print("The mirror string : " + str(res))
#Output : The original string is : void
[END] |
Python - Mirror Image of String | https://www.geeksforgeeks.org/python-mirror-image-of-string/ | # Python3 code to demonstrate working of
# Mirror Image of String
# Using String Slicing and Lookup Dictionary
# Define input string
test_str = "void"
# Define mirror dictionary
mir_dict = {"b": "d", "d": "b", "i": "i", "o": "o", "v": "v", "w": "w", "x": "x"}
# Reverse the input string
rev_str = test_str[::-1]
# Initialize result string
res = ""
# Iterate over reversed string and replace mirrored characters
for ele in rev_str:
if ele in mir_dict:
res += mir_dict[ele]
else:
res = "Not Possible"
break
# Reverse the result string
mir_str = res[::-1]
# Print the original and mirror strings
print("The original string is : " + str(test_str))
print("The mirror string : " + str(mir_str)) |
#Output : The original string is : void | Python - Mirror Image of String
# Python3 code to demonstrate working of
# Mirror Image of String
# Using String Slicing and Lookup Dictionary
# Define input string
test_str = "void"
# Define mirror dictionary
mir_dict = {"b": "d", "d": "b", "i": "i", "o": "o", "v": "v", "w": "w", "x": "x"}
# Reverse the input string
rev_str = test_str[::-1]
# Initialize result string
res = ""
# Iterate over reversed string and replace mirrored characters
for ele in rev_str:
if ele in mir_dict:
res += mir_dict[ele]
else:
res = "Not Possible"
break
# Reverse the result string
mir_str = res[::-1]
# Print the original and mirror strings
print("The original string is : " + str(test_str))
print("The mirror string : " + str(mir_str))
#Output : The original string is : void
[END] |
Python - Replace multiple words with K | https://www.geeksforgeeks.org/python-replace-multiple-words-with-k/?ref=leftbar-rightbar | # 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)) |
#Output : The original string is : Geeksforgeeks is best for geeks and CS | Python - 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))
#Output : The original string is : Geeksforgeeks is best for geeks and CS
[END] |
Python - Replace multiple words with K | https://www.geeksforgeeks.org/python-replace-multiple-words-with-k/?ref=leftbar-rightbar | # 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)) |
#Output : The original string is : Geeksforgeeks is best for geeks and CS | Python - Replace multiple words with K
# 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))
#Output : The original string is : Geeksforgeeks is best for geeks and CS
[END] |
Python - Replace multiple words with K | https://www.geeksforgeeks.org/python-replace-multiple-words-with-k/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Replace multiple words with K
# 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
for i in word_list:
test_str = test_str.replace(i, repl_wrd)
# printing result
print("String after multiple replace : " + str(test_str)) |
#Output : The original string is : Geeksforgeeks is best for geeks and CS | Python - Replace multiple words with K
# Python3 code to demonstrate working of
# Replace multiple words with K
# 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
for i in word_list:
test_str = test_str.replace(i, repl_wrd)
# printing result
print("String after multiple replace : " + str(test_str))
#Output : The original string is : Geeksforgeeks is best for geeks and CS
[END] |
Python - Replace multiple words with K | https://www.geeksforgeeks.org/python-replace-multiple-words-with-k/?ref=leftbar-rightbar | import re
def multiple_replace(text, word_dict):
# create a regular expression pattern from the dictionary keys
pattern = re.compile("|".join(map(re.escape, word_dict.keys())))
# use re.sub to replace the keys with values in the text
return pattern.sub(lambda x: word_dict[x.group(0)], text)
# initialize the input string and dictionary of words to replace
text = "Geeksforgeeks is best for geeks and CS"
word_dict = {"best": "gfg", "CS": "gfg", "for": "gfg"}
# replace the words in the text using the dictionary
result = multiple_replace(text, word_dict)
print("String after multiple replace : " + str(result)) |
#Output : The original string is : Geeksforgeeks is best for geeks and CS | Python - Replace multiple words with K
import re
def multiple_replace(text, word_dict):
# create a regular expression pattern from the dictionary keys
pattern = re.compile("|".join(map(re.escape, word_dict.keys())))
# use re.sub to replace the keys with values in the text
return pattern.sub(lambda x: word_dict[x.group(0)], text)
# initialize the input string and dictionary of words to replace
text = "Geeksforgeeks is best for geeks and CS"
word_dict = {"best": "gfg", "CS": "gfg", "for": "gfg"}
# replace the words in the text using the dictionary
result = multiple_replace(text, word_dict)
print("String after multiple replace : " + str(result))
#Output : The original string is : Geeksforgeeks is best for geeks and CS
[END] |
Python - Replace multiple words with K | https://www.geeksforgeeks.org/python-replace-multiple-words-with-k/?ref=leftbar-rightbar | from functools import reduce
# 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
replace_func = lambda s, w: s.replace(w, repl_wrd)
test_str = reduce(replace_func, word_list, test_str)
# printing result
print("String after multiple replace : " + str(test_str)) |
#Output : The original string is : Geeksforgeeks is best for geeks and CS | Python - Replace multiple words with K
from functools import reduce
# 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
replace_func = lambda s, w: s.replace(w, repl_wrd)
test_str = reduce(replace_func, word_list, test_str)
# printing result
print("String after multiple replace : " + str(test_str))
#Output : The original string is : Geeksforgeeks is best for geeks and CS
[END] |
Python - Replace Different characters in String at Once | https://www.geeksforgeeks.org/python-replace-different-characters-in-string-at-once/ | # Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using join() + generator expression
# initializing string
test_str = "geeksforgeeks is best"
# printing original String
print("The original string is : " + str(test_str))
# initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
# generator expression to construct vals
# join to get string
res = "".join(idx if idx not in map_dict else map_dict[idx] for idx in test_str)
# printing result
print("The converted string : " + str(res)) | #Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61 | Python - Replace Different characters in String at Once
# Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using join() + generator expression
# initializing string
test_str = "geeksforgeeks is best"
# printing original String
print("The original string is : " + str(test_str))
# initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
# generator expression to construct vals
# join to get string
res = "".join(idx if idx not in map_dict else map_dict[idx] for idx in test_str)
# printing result
print("The converted string : " + str(res))
#Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61
[END] |
Python - Replace Different characters in String at Once | https://www.geeksforgeeks.org/python-replace-different-characters-in-string-at-once/ | # Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using regex + lambda
import re
# initializing string
test_str = "geeksforgeeks is best"
# printing original String
print("The original string is : " + str(test_str))
# initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
# using lambda and regex functions to achieve task
res = re.compile("|".join(map_dict.keys())).sub(
lambda ele: map_dict[re.escape(ele.group(0))], test_str
)
# printing result
print("The converted string : " + str(res)) | #Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61 | Python - Replace Different characters in String at Once
# Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using regex + lambda
import re
# initializing string
test_str = "geeksforgeeks is best"
# printing original String
print("The original string is : " + str(test_str))
# initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
# using lambda and regex functions to achieve task
res = re.compile("|".join(map_dict.keys())).sub(
lambda ele: map_dict[re.escape(ele.group(0))], test_str
)
# printing result
print("The converted string : " + str(res))
#Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61
[END] |
Python - Replace Different characters in String at Once | https://www.geeksforgeeks.org/python-replace-different-characters-in-string-at-once/ | # Python3 code to demonstrate working of
# Replace Different characters in String at Once
# initializing string
test_str = "geeksforgeeks is best"
# printing original String
print("The original string is : " + str(test_str))
# initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
for i in test_str:
if i in map_dict.keys():
test_str = test_str.replace(i, map_dict[i])
# printing result
print("The converted string : " + str(test_str)) | #Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61 | Python - Replace Different characters in String at Once
# Python3 code to demonstrate working of
# Replace Different characters in String at Once
# initializing string
test_str = "geeksforgeeks is best"
# printing original String
print("The original string is : " + str(test_str))
# initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
for i in test_str:
if i in map_dict.keys():
test_str = test_str.replace(i, map_dict[i])
# printing result
print("The converted string : " + str(test_str))
#Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61
[END] |
Python - Replace Different characters in String at Once | https://www.geeksforgeeks.org/python-replace-different-characters-in-string-at-once/ | # initializing string
test_str = "geeksforgeeks is best"
# initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
# using list comprehension
new_str = "".join([map_dict.get(char, char) for char in test_str])
# printing result
print("The original string is : " + str(test_str))
print("The converted string : " + str(new_str)) | #Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61 | Python - Replace Different characters in String at Once
# initializing string
test_str = "geeksforgeeks is best"
# initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
# using list comprehension
new_str = "".join([map_dict.get(char, char) for char in test_str])
# printing result
print("The original string is : " + str(test_str))
print("The converted string : " + str(new_str))
#Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61
[END] |
Python - Replace Different characters in String at Once | https://www.geeksforgeeks.org/python-replace-different-characters-in-string-at-once/ | # Importing reduce from functools
from functools import reduce
# Initializing the string
test_str = "geeksforgeeks is best"
# Initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
# Using reduce to replace the characters in the string
# lambda function checks if the character from dictionary is present in the string
# then replace it, otherwise return the string s as it is
# iteratively check each key-value pair in the map_dict
converted_str = reduce(
lambda s, kv: s.replace(kv[0], kv[1]) if kv[0] in s else s,
map_dict.items(),
test_str,
)
# Printing the original and converted string
print("The original string is : " + str(test_str))
print("The converted string : " + str(converted_str))
# This code is contributed by Vinay pinjala | #Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61 | Python - Replace Different characters in String at Once
# Importing reduce from functools
from functools import reduce
# Initializing the string
test_str = "geeksforgeeks is best"
# Initializing mapping dictionary
map_dict = {"e": "1", "b": "6", "i": "4"}
# Using reduce to replace the characters in the string
# lambda function checks if the character from dictionary is present in the string
# then replace it, otherwise return the string s as it is
# iteratively check each key-value pair in the map_dict
converted_str = reduce(
lambda s, kv: s.replace(kv[0], kv[1]) if kv[0] in s else s,
map_dict.items(),
test_str,
)
# Printing the original and converted string
print("The original string is : " + str(test_str))
print("The converted string : " + str(converted_str))
# This code is contributed by Vinay pinjala
#Input : test_str = 'geeksforgeeks is best', map_dict = {'e':'1', 'b':'6'}??????
#Output : g11ksforg11ks is 61
[END] |
Python | Multiple indices Replace in String | https://www.geeksforgeeks.org/python-multiple-indices-replace-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Multiple indices Replace in String
# Using loop + join()
# initializing string
test_str = "geeksforgeeks is best"
# printing original string
print("The original string is : " + test_str)
# initializing list
test_list = [2, 4, 7, 10]
# initializing repl char
repl_char = "*"
# Multiple indices Replace in String
# Using loop + join()
temp = list(test_str)
for idx in test_list:
temp[idx] = repl_char
res = "".join(temp)
# printing result
print("The String after performing replace : " + str(res)) |
#Output : The original string is : geeksforgeeks is best | Python | Multiple indices Replace in String
# Python3 code to demonstrate working of
# Multiple indices Replace in String
# Using loop + join()
# initializing string
test_str = "geeksforgeeks is best"
# printing original string
print("The original string is : " + test_str)
# initializing list
test_list = [2, 4, 7, 10]
# initializing repl char
repl_char = "*"
# Multiple indices Replace in String
# Using loop + join()
temp = list(test_str)
for idx in test_list:
temp[idx] = repl_char
res = "".join(temp)
# printing result
print("The String after performing replace : " + str(res))
#Output : The original string is : geeksforgeeks is best
[END] |
Python | Multiple indices Replace in String | https://www.geeksforgeeks.org/python-multiple-indices-replace-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Multiple indices Replace in String
# Using list comprehension + join()
# initializing string
test_str = "geeksforgeeks is best"
# printing original string
print("The original string is : " + test_str)
# initializing list
test_list = [2, 4, 7, 10]
# initializing repl char
repl_char = "*"
# Multiple indices Replace in String
# Using list comprehension + join()
temp = list(test_str)
res = [repl_char if idx in test_list else ele for idx, ele in enumerate(temp)]
res = "".join(res)
# printing result
print("The String after performing replace : " + str(res)) |
#Output : The original string is : geeksforgeeks is best | Python | Multiple indices Replace in String
# Python3 code to demonstrate working of
# Multiple indices Replace in String
# Using list comprehension + join()
# initializing string
test_str = "geeksforgeeks is best"
# printing original string
print("The original string is : " + test_str)
# initializing list
test_list = [2, 4, 7, 10]
# initializing repl char
repl_char = "*"
# Multiple indices Replace in String
# Using list comprehension + join()
temp = list(test_str)
res = [repl_char if idx in test_list else ele for idx, ele in enumerate(temp)]
res = "".join(res)
# printing result
print("The String after performing replace : " + str(res))
#Output : The original string is : geeksforgeeks is best
[END] |
Python | Multiple indices Replace in String | https://www.geeksforgeeks.org/python-multiple-indices-replace-in-string/?ref=leftbar-rightbar | test_str = "geeksforgeeks is best"
test_list = [2, 4, 7, 10]
repl_char = "*"
res = "".join(
map(lambda x: repl_char if x[0] in test_list else x[1], enumerate(test_str))
)
print("The String after performing replace : " + str(res)) |
#Output : The original string is : geeksforgeeks is best | Python | Multiple indices Replace in String
test_str = "geeksforgeeks is best"
test_list = [2, 4, 7, 10]
repl_char = "*"
res = "".join(
map(lambda x: repl_char if x[0] in test_list else x[1], enumerate(test_str))
)
print("The String after performing replace : " + str(res))
#Output : The original string is : geeksforgeeks is best
[END] |
Python - Ways to remove multiple empty spaces from string list | https://www.geeksforgeeks.org/python-ways-to-remove-multiple-empty-spaces-from-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using loop + strip()
# initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Remove multiple empty spaces from string List
# Using loop + strip()
res = []
for ele in test_list:
if ele.strip():
res.append(ele)
# printing result
print("List after filtering non-empty strings : " + str(res)) |
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best'] | Python - Ways to remove multiple empty spaces from string list
# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using loop + strip()
# initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Remove multiple empty spaces from string List
# Using loop + strip()
res = []
for ele in test_list:
if ele.strip():
res.append(ele)
# printing result
print("List after filtering non-empty strings : " + str(res))
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']
[END] |
Python - Ways to remove multiple empty spaces from string list | https://www.geeksforgeeks.org/python-ways-to-remove-multiple-empty-spaces-from-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using list comprehension + strip()
# initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Remove multiple empty spaces from string List
# Using list comprehension + strip()
res = [ele for ele in test_list if ele.strip()]
# printing result
print("List after filtering non-empty strings : " + str(res)) |
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best'] | Python - Ways to remove multiple empty spaces from string list
# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using list comprehension + strip()
# initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Remove multiple empty spaces from string List
# Using list comprehension + strip()
res = [ele for ele in test_list if ele.strip()]
# printing result
print("List after filtering non-empty strings : " + str(res))
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']
[END] |
Python - Ways to remove multiple empty spaces from string list | https://www.geeksforgeeks.org/python-ways-to-remove-multiple-empty-spaces-from-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using find()
# initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Remove multiple empty spaces from string List
# Using find()
res = []
for ele in test_list:
if ele.find(" ") == -1:
res.append(ele)
# printing result
print("List after filtering non-empty strings : " + str(res)) |
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best'] | Python - Ways to remove multiple empty spaces from string list
# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using find()
# initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
# Remove multiple empty spaces from string List
# Using find()
res = []
for ele in test_list:
if ele.find(" ") == -1:
res.append(ele)
# printing result
print("List after filtering non-empty strings : " + str(res))
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']
[END] |
Python - Ways to remove multiple empty spaces from string list | https://www.geeksforgeeks.org/python-ways-to-remove-multiple-empty-spaces-from-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
res = list(filter(lambda x: x[0].lower() != x[0].upper(), test_list))
# printing result
print("List after filtering non-empty strings : " + str(res)) |
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best'] | Python - Ways to remove multiple empty spaces from string list
# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
res = list(filter(lambda x: x[0].lower() != x[0].upper(), test_list))
# printing result
print("List after filtering non-empty strings : " + str(res))
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']
[END] |
Python - Ways to remove multiple empty spaces from string list | https://www.geeksforgeeks.org/python-ways-to-remove-multiple-empty-spaces-from-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# initializing list
import itertools
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
res = list(itertools.filterfalse(lambda x: x[0].upper() == x[0].lower(), test_list))
# printing result
print("List after filtering non-empty strings : " + str(res)) |
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best'] | Python - Ways to remove multiple empty spaces from string list
# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# initializing list
import itertools
test_list = ["gfg", " ", " ", "is", " ", "best"]
# printing original list
print("The original list is : " + str(test_list))
res = list(itertools.filterfalse(lambda x: x[0].upper() == x[0].lower(), test_list))
# printing result
print("List after filtering non-empty strings : " + str(res))
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']
[END] |
Python - Ways to remove multiple empty spaces from string list | https://www.geeksforgeeks.org/python-ways-to-remove-multiple-empty-spaces-from-string-list/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# Printing original list
print("The original list is : " + str(test_list))
# Remove multiple empty spaces from string List
res = [ele for ele in test_list if not ele.isspace()]
# Printing result
print("List after filtering non-empty strings : " + str(res)) |
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best'] | Python - Ways to remove multiple empty spaces from string list
# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# Printing original list
print("The original list is : " + str(test_list))
# Remove multiple empty spaces from string List
res = [ele for ele in test_list if not ele.isspace()]
# Printing result
print("List after filtering non-empty strings : " + str(res))
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']
[END] |
Python - Ways to remove multiple empty spaces from string list | https://www.geeksforgeeks.org/python-ways-to-remove-multiple-empty-spaces-from-string-list/?ref=leftbar-rightbar | import re
# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# Printing original list
print("The original list is : " + str(test_list))
string = "".join(test_list)
# Remove multiple empty spaces from string List
res = re.findall(r"[a-zA-Z]+", string)
# Printing result
print("List after filtering non-empty strings : " + str(res)) |
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best'] | Python - Ways to remove multiple empty spaces from string list
import re
# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Initializing list
test_list = ["gfg", " ", " ", "is", " ", "best"]
# Printing original list
print("The original list is : " + str(test_list))
string = "".join(test_list)
# Remove multiple empty spaces from string List
res = re.findall(r"[a-zA-Z]+", string)
# Printing result
print("List after filtering non-empty strings : " + str(res))
#Output : The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']
[END] |
Python | Remove punctuation from string | https://www.geeksforgeeks.org/python-remove-punctuation-from-string/?ref=leftbar-rightbar | import string??????test_str = 'Gfg, is best: for ! Geeks ;'??????test_str = test_str.translate????????????????????????(str.maketrans('', '', string.punc |
#Output : Gfg is best for Geeks | Python | Remove punctuation from string
import string??????test_str = 'Gfg, is best: for ! Geeks ;'??????test_str = test_str.translate????????????????????????(str.maketrans('', '', string.punc
#Output : Gfg is best for Geeks
[END] |
Python | Remove punctuation from string | https://www.geeksforgeeks.org/python-remove-punctuation-from-string/?ref=leftbar-rightbar | # initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# initializing punctuations string
punc = """!()-[]{};:'"\,<>./?@#$%^&*_~"""
# Removing punctuations in string
# Using loop + punctuation string
for ele in test_str:
if ele in punc:
test_str = test_str.replace(ele, "")
# printing result
print("The string after punctuation filter : " + test_str) |
#Output : Gfg is best for Geeks | Python | Remove punctuation from string
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# initializing punctuations string
punc = """!()-[]{};:'"\,<>./?@#$%^&*_~"""
# Removing punctuations in string
# Using loop + punctuation string
for ele in test_str:
if ele in punc:
test_str = test_str.replace(ele, "")
# printing result
print("The string after punctuation filter : " + test_str)
#Output : Gfg is best for Geeks
[END] |
Python | Remove punctuation from string | https://www.geeksforgeeks.org/python-remove-punctuation-from-string/?ref=leftbar-rightbar | import re
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# Removing punctuations in string
# Using regex
res = re.sub(r"[^\w\s]", "", test_str)
# printing result
print("The string after punctuation filter : " + res) |
#Output : Gfg is best for Geeks | Python | Remove punctuation from string
import re
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# Removing punctuations in string
# Using regex
res = re.sub(r"[^\w\s]", "", test_str)
# printing result
print("The string after punctuation filter : " + res)
#Output : Gfg is best for Geeks
[END] |
Python | Remove punctuation from string | https://www.geeksforgeeks.org/python-remove-punctuation-from-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Removing punctuations in string
# Using loop + punctuation string
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# initializing punctuations string
punc = """!()-[]{};:'"\,<>./?@#$%^&*_~"""
res = " "
# Removing punctuations in string
# Using loop + punctuation string
for ele in test_str:
if ele not in punc:
res += ele
# printing result
print("The string after punctuation filter : " + res) |
#Output : Gfg is best for Geeks | Python | Remove punctuation from string
# Python3 code to demonstrate working of
# Removing punctuations in string
# Using loop + punctuation string
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# initializing punctuations string
punc = """!()-[]{};:'"\,<>./?@#$%^&*_~"""
res = " "
# Removing punctuations in string
# Using loop + punctuation string
for ele in test_str:
if ele not in punc:
res += ele
# printing result
print("The string after punctuation filter : " + res)
#Output : Gfg is best for Geeks
[END] |
Python | Remove punctuation from string | https://www.geeksforgeeks.org/python-remove-punctuation-from-string/?ref=leftbar-rightbar | def remove_punctuation(test_str):
# Using filter() and lambda function to filter out punctuation characters
result = "".join(
filter(lambda x: x.isalpha() or x.isdigit() or x.isspace(), test_str)
)
return result
test_str = "Gfg, is best : for ! Geeks ;"
print("The original string is : " + test_str)
result = remove_punctuation(test_str)
print("The string after punctuation filter : " + result)
# This code is contributed by Edula Vinay Kumar Reddy |
#Output : Gfg is best for Geeks | Python | Remove punctuation from string
def remove_punctuation(test_str):
# Using filter() and lambda function to filter out punctuation characters
result = "".join(
filter(lambda x: x.isalpha() or x.isdigit() or x.isspace(), test_str)
)
return result
test_str = "Gfg, is best : for ! Geeks ;"
print("The original string is : " + test_str)
result = remove_punctuation(test_str)
print("The string after punctuation filter : " + result)
# This code is contributed by Edula Vinay Kumar Reddy
#Output : Gfg is best for Geeks
[END] |
Python | Remove punctuation from string | https://www.geeksforgeeks.org/python-remove-punctuation-from-string/?ref=leftbar-rightbar | import string
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# Removing punctuations using replace() method
for punctuation in string.punctuation:
test_str = test_str.replace(punctuation, "")
# printing result
print("The string after punctuation filter : " + test_str) |
#Output : Gfg is best for Geeks | Python | Remove punctuation from string
import string
# initializing string
test_str = "Gfg, is best : for ! Geeks ;"
# printing original string
print("The original string is : " + test_str)
# Removing punctuations using replace() method
for punctuation in string.punctuation:
test_str = test_str.replace(punctuation, "")
# printing result
print("The string after punctuation filter : " + test_str)
#Output : Gfg is best for Geeks
[END] |
Python - Similar characters Strings comparison | https://www.geeksforgeeks.org/python-similar-characters-strings-comparison/ | # Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using split() + sorted()
# initializing strings
test_str1 = "e:e:k:s:g"
test_str2 = "g:e:e:k:s"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# initializing delim
delim = ":"
# == operator is used for comparison
res = sorted(test_str1.split(":")) == sorted(test_str2.split(":"))
# printing result
print("Are strings similar : " + str(res)) | #Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True | Python - Similar characters Strings comparison
# Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using split() + sorted()
# initializing strings
test_str1 = "e:e:k:s:g"
test_str2 = "g:e:e:k:s"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# initializing delim
delim = ":"
# == operator is used for comparison
res = sorted(test_str1.split(":")) == sorted(test_str2.split(":"))
# printing result
print("Are strings similar : " + str(res))
#Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True
[END] |
Python - Similar characters Strings comparison | https://www.geeksforgeeks.org/python-similar-characters-strings-comparison/ | # Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using set() + split()
# initializing strings
test_str1 = "e:k:s:g"
test_str2 = "g:e:k:s"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# initializing delim
delim = ":"
# == operator is used for comparison
# removes duplicates and compares
res = set(test_str1.split(":")) == set(test_str2.split(":"))
# printing result
print("Are strings similar : " + str(res)) | #Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True | Python - Similar characters Strings comparison
# Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using set() + split()
# initializing strings
test_str1 = "e:k:s:g"
test_str2 = "g:e:k:s"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# initializing delim
delim = ":"
# == operator is used for comparison
# removes duplicates and compares
res = set(test_str1.split(":")) == set(test_str2.split(":"))
# printing result
print("Are strings similar : " + str(res))
#Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True
[END] |
Python - Similar characters Strings comparison | https://www.geeksforgeeks.org/python-similar-characters-strings-comparison/ | # Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using dictionary
# initializing strings
test_str1 = "e:k:s:g"
test_str2 = "g:e:k:s"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# initializing delim
delim = ":"
# initializing dictionaries
dict1 = {}
dict2 = {}
# loop through characters in string 1
for char in test_str1.split(delim):
if char in dict1:
dict1[char] += 1
else:
dict1[char] = 1
# loop through characters in string 2
for char in test_str2.split(delim):
if char in dict2:
dict2[char] += 1
else:
dict2[char] = 1
# compare dictionaries
res = True
for key in dict1:
if key in dict2 and dict1[key] == dict2[key]:
continue
else:
res = False
break
# printing result
print("Are strings similar : " + str(res)) | #Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True | Python - Similar characters Strings comparison
# Python3 code to demonstrate working of
# Similar characters Strings comparison
# Using dictionary
# initializing strings
test_str1 = "e:k:s:g"
test_str2 = "g:e:k:s"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# initializing delim
delim = ":"
# initializing dictionaries
dict1 = {}
dict2 = {}
# loop through characters in string 1
for char in test_str1.split(delim):
if char in dict1:
dict1[char] += 1
else:
dict1[char] = 1
# loop through characters in string 2
for char in test_str2.split(delim):
if char in dict2:
dict2[char] += 1
else:
dict2[char] = 1
# compare dictionaries
res = True
for key in dict1:
if key in dict2 and dict1[key] == dict2[key]:
continue
else:
res = False
break
# printing result
print("Are strings similar : " + str(res))
#Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True
[END] |
Python - Similar characters Strings comparison | https://www.geeksforgeeks.org/python-similar-characters-strings-comparison/ | # Importing the collections module
from collections import Counter
# Initializing strings
test_str1 = "e:k:s:g"
test_str2 = "g:e:k:s"
# Printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# Initializing empty dictionaries
dict1 = {}
dict2 = {}
# Counting the frequency of each character in both strings and storing the results in the corresponding dictionary
dict1 = Counter(test_str1)
dict2 = Counter(test_str2)
# Comparing the two dictionaries to check if they have the same keys with the same frequency of values
res = dict1 == dict2
# Printing result
print("Are strings similar : " + str(res)) | #Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True | Python - Similar characters Strings comparison
# Importing the collections module
from collections import Counter
# Initializing strings
test_str1 = "e:k:s:g"
test_str2 = "g:e:k:s"
# Printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# Initializing empty dictionaries
dict1 = {}
dict2 = {}
# Counting the frequency of each character in both strings and storing the results in the corresponding dictionary
dict1 = Counter(test_str1)
dict2 = Counter(test_str2)
# Comparing the two dictionaries to check if they have the same keys with the same frequency of values
res = dict1 == dict2
# Printing result
print("Are strings similar : " + str(res))
#Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True
[END] |
Python - Similar characters Strings comparison | https://www.geeksforgeeks.org/python-similar-characters-strings-comparison/ | # initializing strings
test_str1 = "e:k:s:g"
test_str2 = "g:e:k:s"
# initializing delimiter
delim = ":"
# convert strings to lists of characters
list1 = test_str1.split(delim)
list2 = test_str2.split(delim)
# check if both lists have the same characters
res = all(char in list2 for char in list1) and all(char in list1 for char in list2)
# printing result
print("Are strings similar : " + str(res)) | #Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True | Python - Similar characters Strings comparison
# initializing strings
test_str1 = "e:k:s:g"
test_str2 = "g:e:k:s"
# initializing delimiter
delim = ":"
# convert strings to lists of characters
list1 = test_str1.split(delim)
list2 = test_str2.split(delim)
# check if both lists have the same characters
res = all(char in list2 for char in list1) and all(char in list1 for char in list2)
# printing result
print("Are strings similar : " + str(res))
#Input : test_str1 = 'e!e!k!s!g', test_str2 = 'g!e!e!k!s', delim = '!'
#Output : True
[END] |
Python - Remove K length Duplicates from String | https://www.geeksforgeeks.org/python-remove-k-length-duplicates-from-string/ | # Python3 code to demonstrate working of
# Remove K length Duplicates from String
# Using loop + slicing
# initializing strings
test_str = "geeksforfreeksfo"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 3
memo = set()
res = []
for idx in range(0, len(test_str) - K):
# slicing K length substrings
sub = test_str[idx : idx + K]
# checking for presence
if sub not in memo:
memo.add(sub)
res.append(sub)
res = "".join(res[ele] for ele in range(0, len(res), K))
# printing result
print("The modified string : " + str(res)) |
#Output : The original string is : geeksforfreeksfo
| Python - Remove K length Duplicates from String
# Python3 code to demonstrate working of
# Remove K length Duplicates from String
# Using loop + slicing
# initializing strings
test_str = "geeksforfreeksfo"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 3
memo = set()
res = []
for idx in range(0, len(test_str) - K):
# slicing K length substrings
sub = test_str[idx : idx + K]
# checking for presence
if sub not in memo:
memo.add(sub)
res.append(sub)
res = "".join(res[ele] for ele in range(0, len(res), K))
# printing result
print("The modified string : " + str(res))
#Output : The original string is : geeksforfreeksfo
[END] |
Python - Remove suffix from string list | https://www.geeksforgeeks.org/python-remove-suffix-from-string-list/ | # Python3 code to demonstrate working of
# Suffix removal from String list
# using loop + remove() + endswith()
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suffix
suff = "x"
# Suffix removal from String list
# using loop + remove() + endswith()
for word in test_list[:]:
if word.endswith(suff):
test_list.remove(word)
# printing result
print("List after removal of suffix elements : " + str(test_list)) |
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] | Python - Remove suffix from string list
# Python3 code to demonstrate working of
# Suffix removal from String list
# using loop + remove() + endswith()
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suffix
suff = "x"
# Suffix removal from String list
# using loop + remove() + endswith()
for word in test_list[:]:
if word.endswith(suff):
test_list.remove(word)
# printing result
print("List after removal of suffix elements : " + str(test_list))
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
[END] |
Python - Remove suffix from string list | https://www.geeksforgeeks.org/python-remove-suffix-from-string-list/ | # Python3 code to demonstrate working of
# Suffix removal from String list
# using list comprehension + endswith()
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suff
suff = "x"
# Suffix removal from String list
# using list comprehension + endswith()
res = [ele for ele in test_list if not ele.endswith(suff)]
# printing result
print("List after removal of suffix elements : " + str(res)) |
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] | Python - Remove suffix from string list
# Python3 code to demonstrate working of
# Suffix removal from String list
# using list comprehension + endswith()
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suff
suff = "x"
# Suffix removal from String list
# using list comprehension + endswith()
res = [ele for ele in test_list if not ele.endswith(suff)]
# printing result
print("List after removal of suffix elements : " + str(res))
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
[END] |
Python - Remove suffix from string list | https://www.geeksforgeeks.org/python-remove-suffix-from-string-list/ | # Python3 code to demonstrate working of
# Remove prefix strings from list
# using filter + endswith()
# initialize suff
suff = "x"
def eva(x):
return not x.endswith(suff)
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# Remove prefix strings from list
# using filter + endswith()
res = list(filter(eva, test_list))
# printing result
print("List after removal of Kth character of each string : " + str(res)) |
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] | Python - Remove suffix from string list
# Python3 code to demonstrate working of
# Remove prefix strings from list
# using filter + endswith()
# initialize suff
suff = "x"
def eva(x):
return not x.endswith(suff)
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# Remove prefix strings from list
# using filter + endswith()
res = list(filter(eva, test_list))
# printing result
print("List after removal of Kth character of each string : " + str(res))
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
[END] |
Python - Remove suffix from string list | https://www.geeksforgeeks.org/python-remove-suffix-from-string-list/ | # Python3 code to demonstrate working of
# Suffix removal from String list
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suffix
suff = "x"
res = []
# Suffix removal from String list
for i in test_list:
if i[-1] != suff:
res.append(i)
# printing result
print("List after removal of suffix elements : " + str(res)) |
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] | Python - Remove suffix from string list
# Python3 code to demonstrate working of
# Suffix removal from String list
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suffix
suff = "x"
res = []
# Suffix removal from String list
for i in test_list:
if i[-1] != suff:
res.append(i)
# printing result
print("List after removal of suffix elements : " + str(res))
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
[END] |
Python - Remove suffix from string list | https://www.geeksforgeeks.org/python-remove-suffix-from-string-list/ | # Python3 code to demonstrate working of
# Suffix removal from String list
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suffix
suff = "x"
res = []
# Suffix removal from String list
for i in test_list:
if i.find(suff) != len(i) - 1:
res.append(i)
# printing result
print("List after removal of suffix elements : " + str(res)) |
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] | Python - Remove suffix from string list
# Python3 code to demonstrate working of
# Suffix removal from String list
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suffix
suff = "x"
res = []
# Suffix removal from String list
for i in test_list:
if i.find(suff) != len(i) - 1:
res.append(i)
# printing result
print("List after removal of suffix elements : " + str(res))
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
[END] |
Python - Remove suffix from string list | https://www.geeksforgeeks.org/python-remove-suffix-from-string-list/ | # Python3 code to demonstrate working of
# Remove prefix strings from list
# initialize suff
suff = "x"
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# Remove prefix strings from list
res = list(filter(lambda x: x[-1] != suff, test_list))
# printing result
print("List after removal of Kth character of each string : " + str(res)) |
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] | Python - Remove suffix from string list
# Python3 code to demonstrate working of
# Remove prefix strings from list
# initialize suff
suff = "x"
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# Remove prefix strings from list
res = list(filter(lambda x: x[-1] != suff, test_list))
# printing result
print("List after removal of Kth character of each string : " + str(res))
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
[END] |
Python - Remove suffix from string list | https://www.geeksforgeeks.org/python-remove-suffix-from-string-list/ | import re
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suffix
suff = "x$"
# Suffix removal from String list using regular expressions
res = [x for x in test_list if not re.search(suff, x)]
# printing result
print("List after removal of suffix elements : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy |
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] | Python - Remove suffix from string list
import re
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
# initialize suffix
suff = "x$"
# Suffix removal from String list using regular expressions
res = [x for x in test_list if not re.search(suff, x)]
# printing result
print("List after removal of suffix elements : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
[END] |
Python - Remove suffix from string list | https://www.geeksforgeeks.org/python-remove-suffix-from-string-list/ | import pandas as pd
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
suffix = "x"
# Convert the list of strings to a pandas series
s = pd.Series(test_list)
# Remove elements with the suffix
res = s[~s.str.endswith(suffix)].tolist()
print("List after removal of suffix elements :", res)
# This code is contributed by Vinay Pinjala. |
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] | Python - Remove suffix from string list
import pandas as pd
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
suffix = "x"
# Convert the list of strings to a pandas series
s = pd.Series(test_list)
# Remove elements with the suffix
res = s[~s.str.endswith(suffix)].tolist()
print("List after removal of suffix elements :", res)
# This code is contributed by Vinay Pinjala.
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
[END] |
Python - Remove suffix from string list | https://www.geeksforgeeks.org/python-remove-suffix-from-string-list/ | def remove_strings_with_prefix(lst, prefix):
# Base case: if the list is empty, return an empty list
if not lst:
return []
# Recursive case: remove the prefix from the first element in the list
head = lst[0]
if head.endswith(prefix):
# If the head ends with the prefix, skip it and recurse on the rest of the list
return remove_strings_with_prefix(lst[1:], prefix)
else:
# If the head does not end with the prefix, include it and recurse on the rest of the list
return [head] + remove_strings_with_prefix(lst[1:], prefix)
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
suffix = "x"
# Remove elements with the suffix
res = remove_strings_with_prefix(test_list, suffix)
print("List after removal of suffix elements :", res)
# This code is contributed by tvsk. |
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx'] | Python - Remove suffix from string list
def remove_strings_with_prefix(lst, prefix):
# Base case: if the list is empty, return an empty list
if not lst:
return []
# Recursive case: remove the prefix from the first element in the list
head = lst[0]
if head.endswith(prefix):
# If the head ends with the prefix, skip it and recurse on the rest of the list
return remove_strings_with_prefix(lst[1:], prefix)
else:
# If the head does not end with the prefix, include it and recurse on the rest of the list
return [head] + remove_strings_with_prefix(lst[1:], prefix)
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
# printing original list
print("The original list : " + str(test_list))
suffix = "x"
# Remove elements with the suffix
res = remove_strings_with_prefix(test_list, suffix)
print("List after removal of suffix elements :", res)
# This code is contributed by tvsk.
#Output : The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
[END] |
Python Counter| Find all duplicate characters in string | https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/ | def duplicate_characters(string):
# Create an empty dictionary
chars = {}
# Iterate through each character in the string
for char in string:
# If the character is not in the dictionary, add it
if char not in chars:
chars[char] = 1
else:
# If the character is already in the dictionary, increment the count
chars[char] += 1
# Create a list to store the duplicate characters
duplicates = []
# Iterate through the dictionary to find characters with count greater than 1
for char, count in chars.items():
if count > 1:
duplicates.append(char)
return duplicates
# Test cases
print(duplicate_characters("geeksforgeeks")) |
#Output : ['g', 'e', 'k', 's'] | Python Counter| Find all duplicate characters in string
def duplicate_characters(string):
# Create an empty dictionary
chars = {}
# Iterate through each character in the string
for char in string:
# If the character is not in the dictionary, add it
if char not in chars:
chars[char] = 1
else:
# If the character is already in the dictionary, increment the count
chars[char] += 1
# Create a list to store the duplicate characters
duplicates = []
# Iterate through the dictionary to find characters with count greater than 1
for char, count in chars.items():
if count > 1:
duplicates.append(char)
return duplicates
# Test cases
print(duplicate_characters("geeksforgeeks"))
#Output : ['g', 'e', 'k', 's']
[END] |
Python Counter| Find all duplicate characters in string | https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-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)
# Finding no. of occurrence of a character
# and get the index of it.
for letter, count in WC.items():
if count > 1:
print(letter)
# Driver program
if __name__ == "__main__":
input = "geeksforgeeks"
find_dup_char(input) |
#Output : ['g', 'e', 'k', 's'] | Python Counter| 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)
# Finding no. of occurrence of a character
# and get the index of it.
for letter, count in WC.items():
if count > 1:
print(letter)
# Driver program
if __name__ == "__main__":
input = "geeksforgeeks"
find_dup_char(input)
#Output : ['g', 'e', 'k', 's']
[END] |
Python Counter| Find all duplicate characters in string | https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/ | def find_dup_char(input):
x = []
for i in input:
if i not in x and input.count(i) > 1:
x.append(i)
print(" ".join(x))
# Driver program
if __name__ == "__main__":
input = "geeksforgeeks"
find_dup_char(input) |
#Output : ['g', 'e', 'k', 's'] | Python Counter| Find all duplicate characters in string
def find_dup_char(input):
x = []
for i in input:
if i not in x and input.count(i) > 1:
x.append(i)
print(" ".join(x))
# Driver program
if __name__ == "__main__":
input = "geeksforgeeks"
find_dup_char(input)
#Output : ['g', 'e', 'k', 's']
[END] |
Python Counter| Find all duplicate characters in string | https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/ | def find_dup_char(input):
x = filter(lambda x: input.count(x) >= 2, input)
print(" ".join(set(x)))
# Driver Code
if __name__ == "__main__":
input = "geeksforgeeks"
find_dup_char(input) |
#Output : ['g', 'e', 'k', 's'] | Python Counter| Find all duplicate characters in string
def find_dup_char(input):
x = filter(lambda x: input.count(x) >= 2, input)
print(" ".join(set(x)))
# Driver Code
if __name__ == "__main__":
input = "geeksforgeeks"
find_dup_char(input)
#Output : ['g', 'e', 'k', 's']
[END] |
Python Counter| Find all duplicate characters in string | https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/ | def find_duplicate_chars(string):
# Create empty sets to store unique and duplicate characters
unique_chars = set()
duplicate_chars = set()
# Iterate through each character in the string
for char in string:
# If the character is already in unique_chars, it is a duplicate
if char in unique_chars:
duplicate_chars.add(char)
# Otherwise, add it to unique_chars
else:
unique_chars.add(char)
return duplicate_chars
# Example usage:
print(find_duplicate_chars("geeksforgeeks")) # Output: ['e', 'g', 'k', 's'] |
#Output : ['g', 'e', 'k', 's'] | Python Counter| Find all duplicate characters in string
def find_duplicate_chars(string):
# Create empty sets to store unique and duplicate characters
unique_chars = set()
duplicate_chars = set()
# Iterate through each character in the string
for char in string:
# If the character is already in unique_chars, it is a duplicate
if char in unique_chars:
duplicate_chars.add(char)
# Otherwise, add it to unique_chars
else:
unique_chars.add(char)
return duplicate_chars
# Example usage:
print(find_duplicate_chars("geeksforgeeks")) # Output: ['e', 'g', 'k', 's']
#Output : ['g', 'e', 'k', 's']
[END] |
Python Counter| Find all duplicate characters in string | https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/ | from functools import reduce
def find_dup_char(input):
x = reduce(
lambda x, b: x + b if input.rindex(b) != input.index(b) and b not in x else x,
input,
"",
)
print(x)
# Driver Code
if __name__ == "__main__":
input = "geeksforgeeks"
find_dup_char(input) |
#Output : ['g', 'e', 'k', 's'] | Python Counter| Find all duplicate characters in string
from functools import reduce
def find_dup_char(input):
x = reduce(
lambda x, b: x + b if input.rindex(b) != input.index(b) and b not in x else x,
input,
"",
)
print(x)
# Driver Code
if __name__ == "__main__":
input = "geeksforgeeks"
find_dup_char(input)
#Output : ['g', 'e', 'k', 's']
[END] |
Python - Replace duplicate Occurrence in String | https://www.geeksforgeeks.org/python-replace-duplicate-occurrence-in-string/?ref=leftbar-rightbar | # 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)) |
#Output : The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better . | 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))
#Output : The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .
[END] |
Python - Replace duplicate Occurrence in String | https://www.geeksforgeeks.org/python-replace-duplicate-occurrence-in-string/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using keys() + index() + list comprehension
# 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 keys() + index() + list comprehension
test_list = test_str.split(" ")
res = " ".join(
[
repl_dict.get(val)
if val in repl_dict.keys() and test_list.index(val) != idx
else val
for idx, val in enumerate(test_list)
]
)
# printing result
print("The string after replacing : " + str(res)) |
#Output : The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better . | Python - Replace duplicate Occurrence in String
# Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using keys() + index() + list comprehension
# 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 keys() + index() + list comprehension
test_list = test_str.split(" ")
res = " ".join(
[
repl_dict.get(val)
if val in repl_dict.keys() and test_list.index(val) != idx
else val
for idx, val in enumerate(test_list)
]
)
# printing result
print("The string after replacing : " + str(res))
#Output : The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .
[END] |
Python - Replace duplicate Occurrence in String | https://www.geeksforgeeks.org/python-replace-duplicate-occurrence-in-string/?ref=leftbar-rightbar | # 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 set() + loop + list comprehension
words = test_str.split()
seen = set()
res = [
repl_dict[word]
if word in repl_dict and word not in seen and not seen.add(word)
else word
for word in words
]
# join the list of words to form the final string
res = " ".join(res)
# printing result
print("The string after replacing : " + str(res)) |
#Output : The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better . | Python - Replace duplicate Occurrence in String
# 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 set() + loop + list comprehension
words = test_str.split()
seen = set()
res = [
repl_dict[word]
if word in repl_dict and word not in seen and not seen.add(word)
else word
for word in words
]
# join the list of words to form the final string
res = " ".join(res)
# printing result
print("The string after replacing : " + str(res))
#Output : The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .
[END] |
Python - Replace duplicate Occurrence in String | https://www.geeksforgeeks.org/python-replace-duplicate-occurrence-in-string/?ref=leftbar-rightbar | import re
# initializing string
test_str = "Gfg is best . Gfg also has Classes now. \
Classes help understand better . "
# initializing replace mapping
repl_dict = {"Gfg": "It", "Classes": "They"}
# regular expression pattern to match repeated occurrences
pattern = r"\b(" + "|".join(repl_dict.keys()) + r")\b(?=.*\b\1\b)"
# Replace duplicate Occurrence in String
res = re.sub(pattern, lambda match: repl_dict[match.group()], test_str)
# printing result
print("The original string is : " + str(test_str))
print("The string after replacing : " + str(res)) |
#Output : The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better . | Python - Replace duplicate Occurrence in String
import re
# initializing string
test_str = "Gfg is best . Gfg also has Classes now. \
Classes help understand better . "
# initializing replace mapping
repl_dict = {"Gfg": "It", "Classes": "They"}
# regular expression pattern to match repeated occurrences
pattern = r"\b(" + "|".join(repl_dict.keys()) + r")\b(?=.*\b\1\b)"
# Replace duplicate Occurrence in String
res = re.sub(pattern, lambda match: repl_dict[match.group()], test_str)
# printing result
print("The original string is : " + str(test_str))
print("The string after replacing : " + str(res))
#Output : The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .
[END] |
Ways to convert string to dictionaries | https://www.geeksforgeeks.org/ways-to-convert-string-to-dictionary/?ref=leftbar-rightbar | # Python implementation of converting
# a string into a dictionary
# initialising string
str = " Jan = January; Feb = February; Mar = March"
# At first the string will be splitted
# at the occurrence of ';' to divide items
# for the dictionaryand then again splitting
# will be done at occurrence of '=' which
# generates key:value pair for each item
dictionary = dict(subString.split("=") for subString in str.split(";"))
# printing the generated dictionary
print(dictionary) |
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'} | Ways to convert string to dictionaries
# Python implementation of converting
# a string into a dictionary
# initialising string
str = " Jan = January; Feb = February; Mar = March"
# At first the string will be splitted
# at the occurrence of ';' to divide items
# for the dictionaryand then again splitting
# will be done at occurrence of '=' which
# generates key:value pair for each item
dictionary = dict(subString.split("=") for subString in str.split(";"))
# printing the generated dictionary
print(dictionary)
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'}
[END] |
Ways to convert string to dictionaries | https://www.geeksforgeeks.org/ways-to-convert-string-to-dictionary/?ref=leftbar-rightbar | # Python implementation of converting
# a string into a dictionary
# initialising first string
str1 = "Jan, Feb, March"
str2 = "January | February | March"
# splitting first string
# in order to get keys
keys = str1.split(", ")
# splitting second string
# in order to get values
values = str2.split("|")
# declaring the dictionary
dictionary = {}
# Assigning keys and its
# corresponding values in
# the dictionary
for i in range(len(keys)):
dictionary[keys[i]] = values[i]
# printing the generated dictionary
print(dictionary) |
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'} | Ways to convert string to dictionaries
# Python implementation of converting
# a string into a dictionary
# initialising first string
str1 = "Jan, Feb, March"
str2 = "January | February | March"
# splitting first string
# in order to get keys
keys = str1.split(", ")
# splitting second string
# in order to get values
values = str2.split("|")
# declaring the dictionary
dictionary = {}
# Assigning keys and its
# corresponding values in
# the dictionary
for i in range(len(keys)):
dictionary[keys[i]] = values[i]
# printing the generated dictionary
print(dictionary)
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'}
[END] |
Ways to convert string to dictionaries | https://www.geeksforgeeks.org/ways-to-convert-string-to-dictionary/?ref=leftbar-rightbar | # Python implementation of converting
# a string into a dictionary
# initialising first string
str1 = "Jan, Feb, March"
str2 = "January | February | March"
# splitting first string
# in order to get keys
keys = str1.split(", ")
# splitting second string
# in order to get values
values = str2.split("|")
# declaring the dictionary
dictionary = {}
# Assigning keys and its
# corresponding values in
# the dictionary
dictionary = dict(zip(keys, values))
# printing the generated dictionary
print(dictionary) |
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'} | Ways to convert string to dictionaries
# Python implementation of converting
# a string into a dictionary
# initialising first string
str1 = "Jan, Feb, March"
str2 = "January | February | March"
# splitting first string
# in order to get keys
keys = str1.split(", ")
# splitting second string
# in order to get values
values = str2.split("|")
# declaring the dictionary
dictionary = {}
# Assigning keys and its
# corresponding values in
# the dictionary
dictionary = dict(zip(keys, values))
# printing the generated dictionary
print(dictionary)
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'}
[END] |
Ways to convert string to dictionaries | https://www.geeksforgeeks.org/ways-to-convert-string-to-dictionary/?ref=leftbar-rightbar | # Python implementation of converting
# a string into a dictionary
# importing ast module
import ast
# initialising string dictionary
str = '{"Jan" : "January", "Feb" : "February", "Mar" : "March"}'
# converting string into dictionary
dictionary = ast.literal_eval(str)
# printing the generated dictionary
print(dictionary) |
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'} | Ways to convert string to dictionaries
# Python implementation of converting
# a string into a dictionary
# importing ast module
import ast
# initialising string dictionary
str = '{"Jan" : "January", "Feb" : "February", "Mar" : "March"}'
# converting string into dictionary
dictionary = ast.literal_eval(str)
# printing the generated dictionary
print(dictionary)
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'}
[END] |
Ways to convert string to dictionaries | https://www.geeksforgeeks.org/ways-to-convert-string-to-dictionary/?ref=leftbar-rightbar | # Python implementation of converting
# a string into a dictionary
# initialising string
str = " Jan = January; Feb = February; Mar = March"
res = dict()
x = str.split(";")
for i in x:
a = i[: i.index("=")]
b = i[i.index("=") + 1 :]
res[a] = b
# printing the generated dictionary
print(res) |
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'} | Ways to convert string to dictionaries
# Python implementation of converting
# a string into a dictionary
# initialising string
str = " Jan = January; Feb = February; Mar = March"
res = dict()
x = str.split(";")
for i in x:
a = i[: i.index("=")]
b = i[i.index("=") + 1 :]
res[a] = b
# printing the generated dictionary
print(res)
#Output : {' Jan ': ' January', ' Feb ': ' February', ' Mar ': ' March'}
[END] |
Python - Check if two strings are Rotationally Equivalent | https://www.geeksforgeeks.org/python-check-if-two-strings-are-rotationally-equivalent/ | # Python3 code to demonstrate working of
# Check if two strings are Rotationally Equivalent
# Using loop + string slicing
# initializing strings
test_str1 = "geeks"
test_str2 = "eksge"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# Check if two strings are Rotationally Equivalent
# Using loop + string slicing
res = False
for idx in range(len(test_str1)):
if test_str1[idx:] + test_str1[:idx] == test_str2:
res = True
break
# printing result
print("Are two strings Rotationally equal ? : " + str(res)) |
#Output : The original string 1 is : geeks | Python - Check if two strings are Rotationally Equivalent
# Python3 code to demonstrate working of
# Check if two strings are Rotationally Equivalent
# Using loop + string slicing
# initializing strings
test_str1 = "geeks"
test_str2 = "eksge"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# Check if two strings are Rotationally Equivalent
# Using loop + string slicing
res = False
for idx in range(len(test_str1)):
if test_str1[idx:] + test_str1[:idx] == test_str2:
res = True
break
# printing result
print("Are two strings Rotationally equal ? : " + str(res))
#Output : The original string 1 is : geeks
[END] |
Python - Check if two strings are Rotationally Equivalent | https://www.geeksforgeeks.org/python-check-if-two-strings-are-rotationally-equivalent/ | # Python3 code to demonstrate working of
# Check if two strings are Rotationally Equivalent
# Using any() + join() + enumerate()
# initializing strings
test_str1 = "geeks"
test_str2 = "eksge"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# Check if two strings are Rotationally Equivalent
# Using any() + join() + enumerate()
res = any(
"".join([test_str2[idx2 - idx1] for idx2, val2 in enumerate(test_str2)])
== test_str1
for idx1, val1 in enumerate(test_str1)
)
# printing result
print("Are two strings Rotationally equal ? : " + str(res)) |
#Output : The original string 1 is : geeks | Python - Check if two strings are Rotationally Equivalent
# Python3 code to demonstrate working of
# Check if two strings are Rotationally Equivalent
# Using any() + join() + enumerate()
# initializing strings
test_str1 = "geeks"
test_str2 = "eksge"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# Check if two strings are Rotationally Equivalent
# Using any() + join() + enumerate()
res = any(
"".join([test_str2[idx2 - idx1] for idx2, val2 in enumerate(test_str2)])
== test_str1
for idx1, val1 in enumerate(test_str1)
)
# printing result
print("Are two strings Rotationally equal ? : " + str(res))
#Output : The original string 1 is : geeks
[END] |
Python - Check if two strings are Rotationally Equivalent | https://www.geeksforgeeks.org/python-check-if-two-strings-are-rotationally-equivalent/ | test_str1 = "geeks"
test_str2 = "eksge"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# Check if two strings are Rotationally Equivalent
# Using inbuilt function
res = test_str2 in (test_str1 + test_str1)
# printing result
print("Are two strings Rotationally equal ? : " + str(res)) |
#Output : The original string 1 is : geeks | Python - Check if two strings are Rotationally Equivalent
test_str1 = "geeks"
test_str2 = "eksge"
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
# Check if two strings are Rotationally Equivalent
# Using inbuilt function
res = test_str2 in (test_str1 + test_str1)
# printing result
print("Are two strings Rotationally equal ? : " + str(res))
#Output : The original string 1 is : geeks
[END] |
Python | Test if string is subset of another listr | https://www.geeksforgeeks.org/python-test-if-string-is-subset-of-another/ | # Python3 code to demonstrate working of
# Test if string is subset of another
# Using all()
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using all()
res = all(ele in test_str1 for ele in test_str2)
# printing result
print("Does string contains all the characters of other list? : " + str(res)) |
#Output : The original string is : geeksforgeeks | Python | Test if string is subset of another listr
# Python3 code to demonstrate working of
# Test if string is subset of another
# Using all()
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using all()
res = all(ele in test_str1 for ele in test_str2)
# printing result
print("Does string contains all the characters of other list? : " + str(res))
#Output : The original string is : geeksforgeeks
[END] |
Python | Test if string is subset of another listr | https://www.geeksforgeeks.org/python-test-if-string-is-subset-of-another/ | # Python3 code to demonstrate working of
# Test if string is subset of another
# Using issubset()
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using issubset()
res = set(test_str2).issubset(test_str1)
# printing result
print("Does string contains all the characters of other list? : " + str(res)) |
#Output : The original string is : geeksforgeeks | Python | Test if string is subset of another listr
# Python3 code to demonstrate working of
# Test if string is subset of another
# Using issubset()
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using issubset()
res = set(test_str2).issubset(test_str1)
# printing result
print("Does string contains all the characters of other list? : " + str(res))
#Output : The original string is : geeksforgeeks
[END] |
Python | Test if string is subset of another listr | https://www.geeksforgeeks.org/python-test-if-string-is-subset-of-another/ | def is_subset(test_str1, test_str2):
if not test_str2:
return True
if not test_str1:
return False
if test_str1[0] == test_str2[0]:
return is_subset(test_str1[1:], test_str2[1:])
return is_subset(test_str1[1:], test_str2)
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using recursive function
res = is_subset(test_str1, test_str2)
# printing result
print("Does string contains all the characters of other list? : " + str(res))
# this code contributed by tvsk |
#Output : The original string is : geeksforgeeks | Python | Test if string is subset of another listr
def is_subset(test_str1, test_str2):
if not test_str2:
return True
if not test_str1:
return False
if test_str1[0] == test_str2[0]:
return is_subset(test_str1[1:], test_str2[1:])
return is_subset(test_str1[1:], test_str2)
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using recursive function
res = is_subset(test_str1, test_str2)
# printing result
print("Does string contains all the characters of other list? : " + str(res))
# this code contributed by tvsk
#Output : The original string is : geeksforgeeks
[END] |
Python | Test if string is subset of another listr | https://www.geeksforgeeks.org/python-test-if-string-is-subset-of-another/ | # Python3 code to demonstrate working of
# Test if string is subset of another
# Using filter() and lambda
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using filter() and lambda
# Use filter() and lambda to generate a new list of characters from test_str2
# that are also in test_str1, and then check if the length of that list
# is equal to the length of test_str2
result = len(test_str2) == len(list(filter(lambda c: c in test_str1, test_str2)))
# printing result
print("Does string contains all the characters of other list? : " + str(result))
# This code is contributed by Jyothi pinjala |
#Output : The original string is : geeksforgeeks | Python | Test if string is subset of another listr
# Python3 code to demonstrate working of
# Test if string is subset of another
# Using filter() and lambda
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using filter() and lambda
# Use filter() and lambda to generate a new list of characters from test_str2
# that are also in test_str1, and then check if the length of that list
# is equal to the length of test_str2
result = len(test_str2) == len(list(filter(lambda c: c in test_str1, test_str2)))
# printing result
print("Does string contains all the characters of other list? : " + str(result))
# This code is contributed by Jyothi pinjala
#Output : The original string is : geeksforgeeks
[END] |
Python | Test if string is subset of another listr | https://www.geeksforgeeks.org/python-test-if-string-is-subset-of-another/ | # importing Counter from collections module
from collections import Counter
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using Counter() function
count1 = Counter(test_str1)
count2 = Counter(test_str2)
res = not bool(count2 - count1)
# printing result
print("Does string contains all the characters of other list? : " + str(res))
# This code is contributed by Vinay Pinjala. |
#Output : The original string is : geeksforgeeks | Python | Test if string is subset of another listr
# importing Counter from collections module
from collections import Counter
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
# Test if string is subset of another
# Using Counter() function
count1 = Counter(test_str1)
count2 = Counter(test_str2)
res = not bool(count2 - count1)
# printing result
print("Does string contains all the characters of other list? : " + str(res))
# This code is contributed by Vinay Pinjala.
#Output : The original string is : geeksforgeeks
[END] |
Python | Test if string is subset of another listr | https://www.geeksforgeeks.org/python-test-if-string-is-subset-of-another/ | from functools import reduce
def is_subset(str1, str2):
return reduce(lambda a, b: a and b, map(lambda c: c in str1, str2))
# Example usage:
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
print(is_subset(test_str1, test_str2))
# This code is contributed by Rayudu |
#Output : The original string is : geeksforgeeks | Python | Test if string is subset of another listr
from functools import reduce
def is_subset(str1, str2):
return reduce(lambda a, b: a and b, map(lambda c: c in str1, str2))
# Example usage:
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
print(is_subset(test_str1, test_str2))
# This code is contributed by Rayudu
#Output : The original string is : geeksforgeeks
[END] |
Python Program to Generate Random binary string | https://www.geeksforgeeks.org/python-program-to-generate-random-binary-string/?ref=leftbar-rightbar | # Python program for random
# binary string generation
import random
# Function to create the
# random binary string
def rand_key(p):
# Variable to store the
# string
key1 = ""
# Loop to find the string
# of desired length
for i in range(p):
# randint function to generate
# 0, 1 randomly and converting
# the result into str
temp = str(random.randint(0, 1))
# Concatenation the random 0, 1
# to the final result
key1 += temp
return key1
# Driver Code
n = 7
str1 = rand_key(n)
print("Desired length random binary string is: ", str1) | Input: 7
Output: Desired length of random binary string is: 1000001 | Python Program to Generate Random binary string
# Python program for random
# binary string generation
import random
# Function to create the
# random binary string
def rand_key(p):
# Variable to store the
# string
key1 = ""
# Loop to find the string
# of desired length
for i in range(p):
# randint function to generate
# 0, 1 randomly and converting
# the result into str
temp = str(random.randint(0, 1))
# Concatenation the random 0, 1
# to the final result
key1 += temp
return key1
# Driver Code
n = 7
str1 = rand_key(n)
print("Desired length random binary string is: ", str1)
Input: 7
Output: Desired length of random binary string is: 1000001
[END] |
Python Program to Generate Random binary string | https://www.geeksforgeeks.org/python-program-to-generate-random-binary-string/?ref=leftbar-rightbar | import random
def generate_binary_string(n):
# Generate a random number with n bits
number = random.getrandbits(n)
# Convert the number to binary
binary_string = format(number, "0b")
return binary_string
# Test the function
n = 7
print("Random binary string of length {}: {}".format(n, generate_binary_string(n)))
# This code is contributed by Edula Vinay Kumar Reddy | Input: 7
Output: Desired length of random binary string is: 1000001 | Python Program to Generate Random binary string
import random
def generate_binary_string(n):
# Generate a random number with n bits
number = random.getrandbits(n)
# Convert the number to binary
binary_string = format(number, "0b")
return binary_string
# Test the function
n = 7
print("Random binary string of length {}: {}".format(n, generate_binary_string(n)))
# This code is contributed by Edula Vinay Kumar Reddy
Input: 7
Output: Desired length of random binary string is: 1000001
[END] |
Python Program to convert binary to string | https://www.geeksforgeeks.org/convert-binary-to-string-using-python/ | # Python3 code to demonstrate working of
# Converting binary to string
# Using BinarytoDecimal(binary)+chr()
# Defining BinarytoDecimal() function
def BinaryToDecimal(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while binary != 0:
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary // 10
i += 1
return decimal
# Driver's code
# initializing binary data
bin_data = "10001111100101110010111010111110011"
# print binary data
print("The binary value is:", bin_data)
# initializing a empty string for
# storing the string data
str_data = " "
# slicing the input and converting it
# in decimal and then converting it in string
for i in range(0, len(bin_data), 7):
# slicing the bin_data from index range [0, 6]
# and storing it as integer in temp_data
temp_data = int(bin_data[i : i + 7])
# passing temp_data in BinarytoDecimal() function
# to get decimal value of corresponding temp_data
decimal_data = BinaryToDecimal(temp_data)
# Decoding the decimal value returned by
# BinarytoDecimal() function, using chr()
# function which return the string corresponding
# character for given ASCII value, and store it
# in str_data
str_data = str_data + chr(decimal_data)
# printing the result
print("The Binary value after string conversion is:", str_data) |
#Output : The binary value is: 10001111100101110010111010111110011 | Python Program to convert binary to string
# Python3 code to demonstrate working of
# Converting binary to string
# Using BinarytoDecimal(binary)+chr()
# Defining BinarytoDecimal() function
def BinaryToDecimal(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while binary != 0:
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary // 10
i += 1
return decimal
# Driver's code
# initializing binary data
bin_data = "10001111100101110010111010111110011"
# print binary data
print("The binary value is:", bin_data)
# initializing a empty string for
# storing the string data
str_data = " "
# slicing the input and converting it
# in decimal and then converting it in string
for i in range(0, len(bin_data), 7):
# slicing the bin_data from index range [0, 6]
# and storing it as integer in temp_data
temp_data = int(bin_data[i : i + 7])
# passing temp_data in BinarytoDecimal() function
# to get decimal value of corresponding temp_data
decimal_data = BinaryToDecimal(temp_data)
# Decoding the decimal value returned by
# BinarytoDecimal() function, using chr()
# function which return the string corresponding
# character for given ASCII value, and store it
# in str_data
str_data = str_data + chr(decimal_data)
# printing the result
print("The Binary value after string conversion is:", str_data)
#Output : The binary value is: 10001111100101110010111010111110011
[END] |
Python Program to convert binary to string | https://www.geeksforgeeks.org/convert-binary-to-string-using-python/ | # Python3 code to demonstrate working of
# Converting binary to string
# Using BinarytoDecimal(binary)+chr()
# Defining BinarytoDecimal() function
def BinaryToDecimal(binary):
# Using int function to convert to
# string
string = int(binary, 2)
return string
# Driver's code
# initializing binary data
bin_data = "10001111100101110010111010111110011"
# print binary data
print("The binary value is:", bin_data)
# initializing a empty string for
# storing the string data
str_data = " "
# slicing the input and converting it
# in decimal and then converting it in string
for i in range(0, len(bin_data), 7):
# slicing the bin_data from index range [0, 6]
# and storing it in temp_data
temp_data = bin_data[i : i + 7]
# passing temp_data in BinarytoDecimal() function
# to get decimal value of corresponding temp_data
decimal_data = BinaryToDecimal(temp_data)
# Decoding the decimal value returned by
# BinarytoDecimal() function, using chr()
# function which return the string corresponding
# character for given ASCII value, and store it
# in str_data
str_data = str_data + chr(decimal_data)
# printing the result
print("The Binary value after string conversion is:", str_data) |
#Output : The binary value is: 10001111100101110010111010111110011 | Python Program to convert binary to string
# Python3 code to demonstrate working of
# Converting binary to string
# Using BinarytoDecimal(binary)+chr()
# Defining BinarytoDecimal() function
def BinaryToDecimal(binary):
# Using int function to convert to
# string
string = int(binary, 2)
return string
# Driver's code
# initializing binary data
bin_data = "10001111100101110010111010111110011"
# print binary data
print("The binary value is:", bin_data)
# initializing a empty string for
# storing the string data
str_data = " "
# slicing the input and converting it
# in decimal and then converting it in string
for i in range(0, len(bin_data), 7):
# slicing the bin_data from index range [0, 6]
# and storing it in temp_data
temp_data = bin_data[i : i + 7]
# passing temp_data in BinarytoDecimal() function
# to get decimal value of corresponding temp_data
decimal_data = BinaryToDecimal(temp_data)
# Decoding the decimal value returned by
# BinarytoDecimal() function, using chr()
# function which return the string corresponding
# character for given ASCII value, and store it
# in str_data
str_data = str_data + chr(decimal_data)
# printing the result
print("The Binary value after string conversion is:", str_data)
#Output : The binary value is: 10001111100101110010111010111110011
[END] |
Python - Reverse Sort a String | https://www.geeksforgeeks.org/python-reverse-sort-a-string/ | # Python3 code to demonstrate
# Reverse Sort a String
# using join() + sorted() + reverse
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using join() + sorted() + reverse
# Sorting a string
res = "".join(sorted(test_string, reverse=True))
# print result
print("String after reverse sorting : " + str(res)) |
#Output : The original string : geekforgeeks | Python - Reverse Sort a String
# Python3 code to demonstrate
# Reverse Sort a String
# using join() + sorted() + reverse
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using join() + sorted() + reverse
# Sorting a string
res = "".join(sorted(test_string, reverse=True))
# print result
print("String after reverse sorting : " + str(res))
#Output : The original string : geekforgeeks
[END] |
Python - Reverse Sort a String | https://www.geeksforgeeks.org/python-reverse-sort-a-string/ | # Python code to demonstrate
# Reverse Sort a String
# using sorted() + reduce() + lambda
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using sorted() + reduce() + lambda
# Reverse Sort a String
res = reduce(lambda x, y: x + y, sorted(test_string, reverse=True))
# print result
print("String after reverse sorting : " + str(res)) |
#Output : The original string : geekforgeeks | Python - Reverse Sort a String
# Python code to demonstrate
# Reverse Sort a String
# using sorted() + reduce() + lambda
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using sorted() + reduce() + lambda
# Reverse Sort a String
res = reduce(lambda x, y: x + y, sorted(test_string, reverse=True))
# print result
print("String after reverse sorting : " + str(res))
#Output : The original string : geekforgeeks
[END] |
Python - Reverse Sort a String | https://www.geeksforgeeks.org/python-reverse-sort-a-string/ | # Python code to demonstrate
# To Sort and Reverse a String
# using list() + sort() + join()
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using list() + sort() + join
# To Sort and reverse a String
temp = list(test_string)
temp.sort(reverse=True)
res = "".join(temp)
# print result
print("String after reverse sorting : " + res) |
#Output : The original string : geekforgeeks | Python - Reverse Sort a String
# Python code to demonstrate
# To Sort and Reverse a String
# using list() + sort() + join()
# initializing string
test_string = "geekforgeeks"
# printing original string
print("The original string : " + str(test_string))
# using list() + sort() + join
# To Sort and reverse a String
temp = list(test_string)
temp.sort(reverse=True)
res = "".join(temp)
# print result
print("String after reverse sorting : " + res)
#Output : The original string : geekforgeeks
[END] |
Python - Reverse Sort a String | https://www.geeksforgeeks.org/python-reverse-sort-a-string/ | # initializing list
test_list = ["4", "kg", "butter", "for", "40", "bucks"]
# print original list
print("Original List : ", test_list)
# replace substring using map() function and lambda expression
res = list(map(lambda x: x.replace("4", "1"), test_list))
# print modified list
print("Modified List : ", res) |
#Output : The original string : geekforgeeks | Python - Reverse Sort a String
# initializing list
test_list = ["4", "kg", "butter", "for", "40", "bucks"]
# print original list
print("Original List : ", test_list)
# replace substring using map() function and lambda expression
res = list(map(lambda x: x.replace("4", "1"), test_list))
# print modified list
print("Modified List : ", res)
#Output : The original string : geekforgeeks
[END] |
Python - Reverse Sort a String | https://www.geeksforgeeks.org/python-reverse-sort-a-string/ | # initializing list
test_list = ["4", "kg", "butter", "for", "40", "bucks"]
# print original list
print("Original List : ", test_list)
# loop through each element and replace substring
for i in range(len(test_list)):
test_list[i] = test_list[i].replace("4", "1")
# print modified list
print("Modified List : ", test_list) |
#Output : The original string : geekforgeeks | Python - Reverse Sort a String
# initializing list
test_list = ["4", "kg", "butter", "for", "40", "bucks"]
# print original list
print("Original List : ", test_list)
# loop through each element and replace substring
for i in range(len(test_list)):
test_list[i] = test_list[i].replace("4", "1")
# print modified list
print("Modified List : ", test_list)
#Output : The original string : geekforgeeks
[END] |
Python - Reverse Sort a String | https://www.geeksforgeeks.org/python-reverse-sort-a-string/ | # initializing list
test_list = ["4", "kg", "butter", "for", "40", "bucks"]
# using list comprehension to modify the list
modified_list = [elem.replace("4", "1") for elem in test_list]
# printing the modified list
print("Modified List : ", modified_list) |
#Output : The original string : geekforgeeks | Python - Reverse Sort a String
# initializing list
test_list = ["4", "kg", "butter", "for", "40", "bucks"]
# using list comprehension to modify the list
modified_list = [elem.replace("4", "1") for elem in test_list]
# printing the modified list
print("Modified List : ", modified_list)
#Output : The original string : geekforgeeks
[END] |
Python | Check if a Substring is Present in a Given String | https://www.geeksforgeeks.org/python-check-substring-present-given-string/ | # Take input from users
MyString1 = "A geek in need is a geek indeed"
if "need" in MyString1:
print("Yes! it is present in the string")
else:
print("No! it is not present") |
#Output : Example 1: #Input : Substring = "geeks" | Python | Check if a Substring is Present in a Given String
# Take input from users
MyString1 = "A geek in need is a geek indeed"
if "need" in MyString1:
print("Yes! it is present in the string")
else:
print("No! it is not present")
#Output : Example 1: #Input : Substring = "geeks"
[END] |
Python | Check if a Substring is Present in a Given String | https://www.geeksforgeeks.org/python-check-substring-present-given-string/ | # Python code
# To check if a substring is present in a given string or not
# input strings str1 and substr
string = "geeks for geeks" # or string=input() -> taking input from the user
substring = "geeks" # or substring=input()
# splitting words in a given string
s = string.split()
# checking condition
# if substring is present in the given string then it gives output as yes
if substring in s:
print("yes")
else:
print("no") |
#Output : Example 1: #Input : Substring = "geeks" | Python | Check if a Substring is Present in a Given String
# Python code
# To check if a substring is present in a given string or not
# input strings str1 and substr
string = "geeks for geeks" # or string=input() -> taking input from the user
substring = "geeks" # or substring=input()
# splitting words in a given string
s = string.split()
# checking condition
# if substring is present in the given string then it gives output as yes
if substring in s:
print("yes")
else:
print("no")
#Output : Example 1: #Input : Substring = "geeks"
[END] |
Python | Check if a Substring is Present in a Given String | https://www.geeksforgeeks.org/python-check-substring-present-given-string/ | # 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) |
#Output : Example 1: #Input : Substring = "geeks" | Python | Check if a Substring is Present in a Given String
# 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)
#Output : Example 1: #Input : Substring = "geeks"
[END] |
Python | Check if a Substring is Present in a Given String | https://www.geeksforgeeks.org/python-check-substring-present-given-string/ | def check(s2, s1):
if s2.count(s1) > 0:
print("YES")
else:
print("NO")
s2 = "A geek in need is a geek indeed"
s1 = "geeks"
check(s2, s1) |
#Output : Example 1: #Input : Substring = "geeks" | Python | Check if a Substring is Present in a Given String
def check(s2, s1):
if s2.count(s1) > 0:
print("YES")
else:
print("NO")
s2 = "A geek in need is a geek indeed"
s1 = "geeks"
check(s2, s1)
#Output : Example 1: #Input : Substring = "geeks"
[END] |
Python | Check if a Substring is Present in a Given String | https://www.geeksforgeeks.org/python-check-substring-present-given-string/ | any_string = "Geeks for Geeks substring "
start = 0
end = 1000
print(any_string.index("substring", start, end)) |
#Output : Example 1: #Input : Substring = "geeks" | Python | Check if a Substring is Present in a Given String
any_string = "Geeks for Geeks substring "
start = 0
end = 1000
print(any_string.index("substring", start, end))
#Output : Example 1: #Input : Substring = "geeks"
[END] |
Python | Check if a Substring is Present in a Given String | https://www.geeksforgeeks.org/python-check-substring-present-given-string/ | a = ["Geeks-13", "for-56", "Geeks-78", "xyz-46"]
for i in a:
if i.__contains__("Geeks"):
print(f"Yes! {i} is containing.") |
#Output : Example 1: #Input : Substring = "geeks" | Python | Check if a Substring is Present in a Given String
a = ["Geeks-13", "for-56", "Geeks-78", "xyz-46"]
for i in a:
if i.__contains__("Geeks"):
print(f"Yes! {i} is containing.")
#Output : Example 1: #Input : Substring = "geeks"
[END] |