Description
stringlengths 9
105
| Link
stringlengths 45
135
| Code
stringlengths 10
26.8k
| Test_Case
stringlengths 9
202
| Merge
stringlengths 63
27k
|
---|---|---|---|---|
Python - Prefix frequency in string list | https://www.geeksforgeeks.org/python-prefix-frequency-in-string-list/?ref=leftbar-rightbar | from functools import reduce
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# Initializing substring
test_sub = "gfg"
# using lambda function to check if a string starts with the given substring
count_func = lambda count, string: count + 1 if string.startswith(test_sub) else count
# using reduce() function to apply the lambda function to each element of the list
res = reduce(count_func, test_list, 0)
# printing original list
print("The original list is : " + str(test_list))
# printing result
print("Strings count with matching frequency : " + str(res)) |
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses'] | Python - Prefix frequency in string list
from functools import reduce
# Initializing list
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# Initializing substring
test_sub = "gfg"
# using lambda function to check if a string starts with the given substring
count_func = lambda count, string: count + 1 if string.startswith(test_sub) else count
# using reduce() function to apply the lambda function to each element of the list
res = reduce(count_func, test_list, 0)
# printing original list
print("The original list is : " + str(test_list))
# printing result
print("Strings count with matching frequency : " + str(res))
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
[END] |
Python - Prefix frequency in string list | https://www.geeksforgeeks.org/python-prefix-frequency-in-string-list/?ref=leftbar-rightbar | # Initialize a list of strings
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# Initialize a substring to find in the list
test_sub = "gfg"
# Create a new iterator that contains only the elements in the list that start with the substring
new_iter = filter(lambda element: element.startswith(test_sub), test_list)
# Count the number of elements in the iterator using the len() method
count = len(list(new_iter))
# Print the original list of strings
print("The original list is : " + str(test_list))
# Print the number of strings in the list that start with the substring
print("Strings count with matching frequency: ", count) |
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses'] | Python - Prefix frequency in string list
# Initialize a list of strings
test_list = ["gfgisbest", "geeks", "gfgfreak", "gfgCS", "Gcourses"]
# Initialize a substring to find in the list
test_sub = "gfg"
# Create a new iterator that contains only the elements in the list that start with the substring
new_iter = filter(lambda element: element.startswith(test_sub), test_list)
# Count the number of elements in the iterator using the len() method
count = len(list(new_iter))
# Print the original list of strings
print("The original list is : " + str(test_list))
# Print the number of strings in the list that start with the substring
print("Strings count with matching frequency: ", count)
#Output : The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
[END] |
Python - Split string of list on K character | https://www.geeksforgeeks.org/python-split-string-of-list-on-k-character/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Split String of list on K character
# using loop + split()
# Initializing list
test_list = ["Gfg is best", "for Geeks", "Preparing"]
# printing original list
print("The original list is : " + str(test_list))
K = " "
# Split String of list on K character
# using loop + split()
res = []
for ele in test_list:
sub = ele.split(K)
res.extend(sub)
# printing result
print("The extended list after split strings : " + str(res)) |
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing'] | Python - Split string of list on K character
# Python3 code to demonstrate
# Split String of list on K character
# using loop + split()
# Initializing list
test_list = ["Gfg is best", "for Geeks", "Preparing"]
# printing original list
print("The original list is : " + str(test_list))
K = " "
# Split String of list on K character
# using loop + split()
res = []
for ele in test_list:
sub = ele.split(K)
res.extend(sub)
# printing result
print("The extended list after split strings : " + str(res))
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
[END] |
Python - Split string of list on K character | https://www.geeksforgeeks.org/python-split-string-of-list-on-k-character/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Split String of list on K character
# using join() + split()
# Initializing list
test_list = ["Gfg is best", "for Geeks", "Preparing"]
# printing original list
print("The original list is : " + str(test_list))
K = " "
# Split String of list on K character
# using join() + split()
res = K.join(test_list).split(K)
# printing result
print("The extended list after split strings : " + str(res)) |
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing'] | Python - Split string of list on K character
# Python3 code to demonstrate
# Split String of list on K character
# using join() + split()
# Initializing list
test_list = ["Gfg is best", "for Geeks", "Preparing"]
# printing original list
print("The original list is : " + str(test_list))
K = " "
# Split String of list on K character
# using join() + split()
res = K.join(test_list).split(K)
# printing result
print("The extended list after split strings : " + str(res))
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
[END] |
Python - Split string of list on K character | https://www.geeksforgeeks.org/python-split-string-of-list-on-k-character/?ref=leftbar-rightbar | import itertools
test_list = ["Gfg is best", "for Geeks", "Preparing"]
K = " "
# Split String of list on K character using itertools.chain and str.split
result = list(itertools.chain(*(s.split(K) for s in test_list)))
print("The extended list after split strings:", result)
# This code is contributed by Edula Vinay Kumar Reddy |
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing'] | Python - Split string of list on K character
import itertools
test_list = ["Gfg is best", "for Geeks", "Preparing"]
K = " "
# Split String of list on K character using itertools.chain and str.split
result = list(itertools.chain(*(s.split(K) for s in test_list)))
print("The extended list after split strings:", result)
# This code is contributed by Edula Vinay Kumar Reddy
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
[END] |
Python - Split string of list on K character | https://www.geeksforgeeks.org/python-split-string-of-list-on-k-character/?ref=leftbar-rightbar | test_list = ["Gfg is best", "for Geeks", "Preparing"]
K = " "
# Split String of list on K character using List Comprehension
result = [word for phrase in test_list for word in phrase.split(K)]
print("The extended list after split strings:", result) |
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing'] | Python - Split string of list on K character
test_list = ["Gfg is best", "for Geeks", "Preparing"]
K = " "
# Split String of list on K character using List Comprehension
result = [word for phrase in test_list for word in phrase.split(K)]
print("The extended list after split strings:", result)
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
[END] |
Python - Split string of list on K character | https://www.geeksforgeeks.org/python-split-string-of-list-on-k-character/?ref=leftbar-rightbar | def split_list_on_char(test_list, char):
result = []
for item in test_list:
if isinstance(item, str):
subitems = split_string_on_char(item, char)
result.extend(subitems)
else:
result.append(item)
return result
def split_string_on_char(string, char):
if char not in string:
return [string]
index = string.index(char)
left = string[:index]
right = string[index + 1 :]
return [left] + split_string_on_char(right, char)
test_list = ["Gfg is best", "for Geeks", "Preparing"]
result = split_list_on_char(test_list, " ")
print("The extended list after split strings:", result) |
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing'] | Python - Split string of list on K character
def split_list_on_char(test_list, char):
result = []
for item in test_list:
if isinstance(item, str):
subitems = split_string_on_char(item, char)
result.extend(subitems)
else:
result.append(item)
return result
def split_string_on_char(string, char):
if char not in string:
return [string]
index = string.index(char)
left = string[:index]
right = string[index + 1 :]
return [left] + split_string_on_char(right, char)
test_list = ["Gfg is best", "for Geeks", "Preparing"]
result = split_list_on_char(test_list, " ")
print("The extended list after split strings:", result)
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
[END] |
Python - Split string of list on K character | https://www.geeksforgeeks.org/python-split-string-of-list-on-k-character/?ref=leftbar-rightbar | from functools import reduce
def split_list_on_char(test_list, char):
return reduce(
lambda acc, item: acc + split_string_on_char(item, char)
if isinstance(item, str)
else acc + [item],
test_list,
[],
)
def split_string_on_char(string, char):
if char not in string:
return [string]
index = string.index(char)
left = string[:index]
right = string[index + 1 :]
return [left] + split_string_on_char(right, char)
test_list = ["Gfg is best", "for Geeks", "Preparing"]
result = split_list_on_char(test_list, " ")
print("The extended list after split strings:", result)
# This code is contributed by Jyothi pinjala. |
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing'] | Python - Split string of list on K character
from functools import reduce
def split_list_on_char(test_list, char):
return reduce(
lambda acc, item: acc + split_string_on_char(item, char)
if isinstance(item, str)
else acc + [item],
test_list,
[],
)
def split_string_on_char(string, char):
if char not in string:
return [string]
index = string.index(char)
left = string[:index]
right = string[index + 1 :]
return [left] + split_string_on_char(right, char)
test_list = ["Gfg is best", "for Geeks", "Preparing"]
result = split_list_on_char(test_list, " ")
print("The extended list after split strings:", result)
# This code is contributed by Jyothi pinjala.
#Output : The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
[END] |
Python - Split String on Prefix Occurrence | https://www.geeksforgeeks.org/python-split-strings-on-prefix-occurrence/ | # Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + startswith()
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix
pref = "geek"
res = []
for val in test_list:
# checking for prefix
if val.startswith(pref):
# if pref found, start new list
res.append([val])
else:
# else append in current list
res[-1].append(val)
# printing result
print("Prefix Split List : " + str(res)) |
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS'] | Python - Split String on Prefix Occurrence
# Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + startswith()
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix
pref = "geek"
res = []
for val in test_list:
# checking for prefix
if val.startswith(pref):
# if pref found, start new list
res.append([val])
else:
# else append in current list
res[-1].append(val)
# printing result
print("Prefix Split List : " + str(res))
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
[END] |
Python - Split String on Prefix Occurrence | https://www.geeksforgeeks.org/python-split-strings-on-prefix-occurrence/ | # Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + zip_longest() + startswith()
from itertools import zip_longest
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix
pref = "geek"
res, temp = [], []
for x, y in zip_longest(test_list, test_list[1:]):
temp.append(x)
# if prefix is found, split and start new list
if y and y.startswith(pref):
res.append(temp)
temp = []
res.append(temp)
# printing result
print("Prefix Split List : " + str(res)) |
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS'] | Python - Split String on Prefix Occurrence
# Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + zip_longest() + startswith()
from itertools import zip_longest
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix
pref = "geek"
res, temp = [], []
for x, y in zip_longest(test_list, test_list[1:]):
temp.append(x)
# if prefix is found, split and start new list
if y and y.startswith(pref):
res.append(temp)
temp = []
res.append(temp)
# printing result
print("Prefix Split List : " + str(res))
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
[END] |
Python - Split String on Prefix Occurrence | https://www.geeksforgeeks.org/python-split-strings-on-prefix-occurrence/ | def split_list_at_prefix(test_list, pref):
# Initialize an empty list to hold the sublists.
result = []
# Initialize an empty sublist to hold the strings that come before the prefix.
sublist = []
# Iterate over the input list of strings.
for string in test_list:
# For each string, check if it starts with the given prefix.
if string.startswith(pref):
# If the string starts with the prefix, add the current sublist to the result list,
# and create a new empty sublist.
if sublist:
result.append(sublist)
sublist = []
# If the string does not start with the prefix, add it to the current sublist.
sublist.append(string)
# If the loop is complete, add the final sublist to the result list.
if sublist:
result.append(sublist)
# Return the result list.
return result
test_list = ["geeksforgeeks", "best", "geeks", "and"]
prefix = "geek"
result = split_list_at_prefix(test_list, prefix)
print(result) |
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS'] | Python - Split String on Prefix Occurrence
def split_list_at_prefix(test_list, pref):
# Initialize an empty list to hold the sublists.
result = []
# Initialize an empty sublist to hold the strings that come before the prefix.
sublist = []
# Iterate over the input list of strings.
for string in test_list:
# For each string, check if it starts with the given prefix.
if string.startswith(pref):
# If the string starts with the prefix, add the current sublist to the result list,
# and create a new empty sublist.
if sublist:
result.append(sublist)
sublist = []
# If the string does not start with the prefix, add it to the current sublist.
sublist.append(string)
# If the loop is complete, add the final sublist to the result list.
if sublist:
result.append(sublist)
# Return the result list.
return result
test_list = ["geeksforgeeks", "best", "geeks", "and"]
prefix = "geek"
result = split_list_at_prefix(test_list, prefix)
print(result)
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
[END] |
Python - Split String on Prefix Occurrence | https://www.geeksforgeeks.org/python-split-strings-on-prefix-occurrence/ | # Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + find()
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix
pref = "geek"
res = []
for val in test_list:
# checking for prefix
if val.find(pref) == 0:
# if pref found, start new list
res.append([val])
else:
# else append in current list
res[-1].append(val)
# printing result
print("Prefix Split List : " + str(res)) |
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS'] | Python - Split String on Prefix Occurrence
# Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + find()
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix
pref = "geek"
res = []
for val in test_list:
# checking for prefix
if val.find(pref) == 0:
# if pref found, start new list
res.append([val])
else:
# else append in current list
res[-1].append(val)
# printing result
print("Prefix Split List : " + str(res))
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
[END] |
Python - Split String on Prefix Occurrence | https://www.geeksforgeeks.org/python-split-strings-on-prefix-occurrence/ | # Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using itertools.groupby()
from itertools import groupby
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix
pref = "geek"
# Using groupby() + startswith()
res = []
for k, g in groupby(test_list, lambda x: x.startswith(pref)):
if k:
res.append(list(g))
else:
if res:
res[-1].extend(list(g))
# printing result
print("Prefix Split List : " + str(res))
# This code is contributed by Jyothi Pinjala. |
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS'] | Python - Split String on Prefix Occurrence
# Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using itertools.groupby()
from itertools import groupby
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix
pref = "geek"
# Using groupby() + startswith()
res = []
for k, g in groupby(test_list, lambda x: x.startswith(pref)):
if k:
res.append(list(g))
else:
if res:
res[-1].extend(list(g))
# printing result
print("Prefix Split List : " + str(res))
# This code is contributed by Jyothi Pinjala.
#Output : The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
[END] |
Python program to Replace all Characters of a List Except the given character | https://www.geeksforgeeks.org/python-program-to-replace-all-characters-of-a-list-except-the-given-character/ | # Python3 code to demonstrate working of
# Replace all Characters Except K
# Using list comprehension and conditional expressions
# initializing lists
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
# printing original list
print("The original list : " + str(test_list))
# initializing repl_chr
repl_chr = "$"
# initializing retain chararter
ret_chr = "G"
# list comprehension to remake list after replacement
res = [ele if ele == ret_chr else repl_chr for ele in test_list]
# printing result
print("List after replacement : " + str(res)) |
#Output : The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'] | Python program to Replace all Characters of a List Except the given character
# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using list comprehension and conditional expressions
# initializing lists
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
# printing original list
print("The original list : " + str(test_list))
# initializing repl_chr
repl_chr = "$"
# initializing retain chararter
ret_chr = "G"
# list comprehension to remake list after replacement
res = [ele if ele == ret_chr else repl_chr for ele in test_list]
# printing result
print("List after replacement : " + str(res))
#Output : The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
[END] |
Python program to Replace all Characters of a List Except the given character | https://www.geeksforgeeks.org/python-program-to-replace-all-characters-of-a-list-except-the-given-character/ | # Python3 code to demonstrate working of
# Replace all Characters Except K
# Using map() + lambda
# initializing lists
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
# printing original list
print("The original list : " + str(test_list))
# initializing repl_chr
repl_chr = "$"
# initializing retain chararter
ret_chr = "G"
# using map() to extend logic to each element of list
res = list(map(lambda ele: ret_chr if ele == ret_chr else repl_chr, test_list))
# printing result
print("List after replacement : " + str(res)) |
#Output : The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'] | Python program to Replace all Characters of a List Except the given character
# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using map() + lambda
# initializing lists
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
# printing original list
print("The original list : " + str(test_list))
# initializing repl_chr
repl_chr = "$"
# initializing retain chararter
ret_chr = "G"
# using map() to extend logic to each element of list
res = list(map(lambda ele: ret_chr if ele == ret_chr else repl_chr, test_list))
# printing result
print("List after replacement : " + str(res))
#Output : The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
[END] |
Python program to Replace all Characters of a List Except the given character | https://www.geeksforgeeks.org/python-program-to-replace-all-characters-of-a-list-except-the-given-character/ | # Python3 code to demonstrate working of
# Replace all Characters Except K
# Using for loop
# initializing lists
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
# printing original list
print("The original list : " + str(test_list))
# initializing repl_chr
repl_chr = "$"
# initializing retain chararter
ret_chr = "G"
# creating an empty list to store the modified characters
res = []
# iterating through the list and replacing the characters
for ele in test_list:
if ele == ret_chr:
res.append(ele)
else:
res.append(repl_chr)
# printing result
print("List after replacement : " + str(res)) |
#Output : The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'] | Python program to Replace all Characters of a List Except the given character
# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using for loop
# initializing lists
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
# printing original list
print("The original list : " + str(test_list))
# initializing repl_chr
repl_chr = "$"
# initializing retain chararter
ret_chr = "G"
# creating an empty list to store the modified characters
res = []
# iterating through the list and replacing the characters
for ele in test_list:
if ele == ret_chr:
res.append(ele)
else:
res.append(repl_chr)
# printing result
print("List after replacement : " + str(res))
#Output : The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
[END] |
Python - Remove words containing list characters | https://www.geeksforgeeks.org/python-remove-words-containing-list-characters/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Remove words containing list characters
# using list comprehension + all()
from itertools import groupby
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
# using list comprehension + all()
res = [ele for ele in test_list if all(ch not in ele for ch in char_list)]
# printing result
print("The filtered strings are : " + str(res)) |
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] | Python - Remove words containing list characters
# Python3 code to demonstrate
# Remove words containing list characters
# using list comprehension + all()
from itertools import groupby
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
# using list comprehension + all()
res = [ele for ele in test_list if all(ch not in ele for ch in char_list)]
# printing result
print("The filtered strings are : " + str(res))
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
[END] |
Python - Remove words containing list characters | https://www.geeksforgeeks.org/python-remove-words-containing-list-characters/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Remove words containing list characters
# using loop
from itertools import groupby
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
# using loop
res = []
flag = 1
for ele in test_list:
for idx in char_list:
if idx not in ele:
flag = 1
else:
flag = 0
break
if flag == 1:
res.append(ele)
# printing result
print("The filtered strings are : " + str(res)) |
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] | Python - Remove words containing list characters
# Python3 code to demonstrate
# Remove words containing list characters
# using loop
from itertools import groupby
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
# using loop
res = []
flag = 1
for ele in test_list:
for idx in char_list:
if idx not in ele:
flag = 1
else:
flag = 0
break
if flag == 1:
res.append(ele)
# printing result
print("The filtered strings are : " + str(res))
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
[END] |
Python - Remove words containing list characters | https://www.geeksforgeeks.org/python-remove-words-containing-list-characters/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Remove words containing list characters
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
res = []
for i in test_list:
x = i
for j in char_list:
i = i.replace(j, "")
if len(i) == len(x):
res.append(i)
# printing result
print("The filtered strings are : " + str(res)) |
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] | Python - Remove words containing list characters
# Python3 code to demonstrate
# Remove words containing list characters
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
res = []
for i in test_list:
x = i
for j in char_list:
i = i.replace(j, "")
if len(i) == len(x):
res.append(i)
# printing result
print("The filtered strings are : " + str(res))
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
[END] |
Python - Remove words containing list characters | https://www.geeksforgeeks.org/python-remove-words-containing-list-characters/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Remove words containing list characters
from collections import Counter
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
res = []
freqCharList = Counter(char_list)
for i in test_list:
unique = True
for char in i:
if char in freqCharList.keys():
unique = False
break
if unique:
res.append(i)
# printing result
print("The filtered strings are : " + str(res)) |
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] | Python - Remove words containing list characters
# Python3 code to demonstrate
# Remove words containing list characters
from collections import Counter
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
res = []
freqCharList = Counter(char_list)
for i in test_list:
unique = True
for char in i:
if char in freqCharList.keys():
unique = False
break
if unique:
res.append(i)
# printing result
print("The filtered strings are : " + str(res))
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
[END] |
Python - Remove words containing list characters | https://www.geeksforgeeks.org/python-remove-words-containing-list-characters/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Remove words containing list characters
from itertools import groupby
import operator as op
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
# using loop
res = []
flag = 1
for ele in test_list:
for idx in char_list:
if op.countOf(ele, idx) == 0:
flag = 1
else:
flag = 0
break
if flag == 1:
res.append(ele)
# printing result
print("The filtered strings are : " + str(res)) |
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] | Python - Remove words containing list characters
# Python3 code to demonstrate
# Remove words containing list characters
from itertools import groupby
import operator as op
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
# using loop
res = []
flag = 1
for ele in test_list:
for idx in char_list:
if op.countOf(ele, idx) == 0:
flag = 1
else:
flag = 0
break
if flag == 1:
res.append(ele)
# printing result
print("The filtered strings are : " + str(res))
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
[END] |
Python - Remove words containing list characters | https://www.geeksforgeeks.org/python-remove-words-containing-list-characters/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Remove words containing list characters
def remove_words(start, lst, charlst, newlist=[]):
if start == len(lst):
return newlist
flag = 0
for i in charlst:
if i in lst[start]:
flag = 1
if flag == 0:
newlist.append(lst[start])
return remove_words(start + 1, lst, charlst, newlist)
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
# using recursive function
res = remove_words(0, test_list, char_list)
# printing result
print("The filtered strings are : " + str(res))
# this code contributed by tvsk |
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] | Python - Remove words containing list characters
# Python3 code to demonstrate
# Remove words containing list characters
def remove_words(start, lst, charlst, newlist=[]):
if start == len(lst):
return newlist
flag = 0
for i in charlst:
if i in lst[start]:
flag = 1
if flag == 0:
newlist.append(lst[start])
return remove_words(start + 1, lst, charlst, newlist)
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
# using recursive function
res = remove_words(0, test_list, char_list)
# printing result
print("The filtered strings are : " + str(res))
# this code contributed by tvsk
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
[END] |
Python - Remove words containing list characters | https://www.geeksforgeeks.org/python-remove-words-containing-list-characters/?ref=leftbar-rightbar | test_list = ["gfg", "is", "best", "for", "geeks"]
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
res = list(filter(lambda x: not any(y in x for y in char_list), test_list))
print(res) |
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] | Python - Remove words containing list characters
test_list = ["gfg", "is", "best", "for", "geeks"]
char_list = ["g", "o"]
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
res = list(filter(lambda x: not any(y in x for y in char_list), test_list))
print(res)
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
[END] |
Python - Remove words containing list characters | https://www.geeksforgeeks.org/python-remove-words-containing-list-characters/?ref=leftbar-rightbar | # Python3 code to demonstrate
# Remove words containing list characters
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = set(["g", "o"])
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
res = list(filter(lambda x: not set(x).intersection(char_list), test_list))
# printing result
print("The filtered strings are : " + str(res)) |
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] | Python - Remove words containing list characters
# Python3 code to demonstrate
# Remove words containing list characters
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
# initializing char list
char_list = set(["g", "o"])
# printing original list
print("The original list is : " + str(test_list))
# printing character list
print("The character list is : " + str(char_list))
# Remove words containing list characters
res = list(filter(lambda x: not set(x).intersection(char_list), test_list))
# printing result
print("The filtered strings are : " + str(res))
#Output : The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
[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 - Add Space between Potential Words | https://www.geeksforgeeks.org/python-add-space-between-potential-words/ | # Python3 code to demonstrate working of
# Add Space between Potential Words
# Using loop + join()
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
res = []
# loop to iterate all strings
for ele in test_list:
temp = [[]]
for char in ele:
# checking for upper case character
if char.isupper():
temp.append([])
# appending character at latest list
temp[-1].append(char)
# joining lists after adding space
res.append(" ".join("".join(ele) for ele in temp))
# printing result
print("The space added list of strings : " + str(res)) |
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience'] | Python - Add Space between Potential Words
# Python3 code to demonstrate working of
# Add Space between Potential Words
# Using loop + join()
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
res = []
# loop to iterate all strings
for ele in test_list:
temp = [[]]
for char in ele:
# checking for upper case character
if char.isupper():
temp.append([])
# appending character at latest list
temp[-1].append(char)
# joining lists after adding space
res.append(" ".join("".join(ele) for ele in temp))
# printing result
print("The space added list of strings : " + str(res))
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
[END] |
Python - Add Space between Potential Words | https://www.geeksforgeeks.org/python-add-space-between-potential-words/ | # Python3 code to demonstrate working of
# Add Space between Potential Words
# Using regex() + list comprehension
import re
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
# using regex() to perform task
res = [re.sub(r"(\w)([A-Z])", r"\1 \2", ele) for ele in test_list]
# printing result
print("The space added list of strings : " + str(res)) |
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience'] | Python - Add Space between Potential Words
# Python3 code to demonstrate working of
# Add Space between Potential Words
# Using regex() + list comprehension
import re
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
# using regex() to perform task
res = [re.sub(r"(\w)([A-Z])", r"\1 \2", ele) for ele in test_list]
# printing result
print("The space added list of strings : " + str(res))
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
[END] |
Python - Add Space between Potential Words | https://www.geeksforgeeks.org/python-add-space-between-potential-words/ | # Python3 code to demonstrate working of
# Add Space between Potential Words
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
res = []
for i in test_list:
for j in i:
if j.isupper():
i = i.replace(j, " " + j)
res.append(i)
# printing result
print("The space added list of strings : " + str(res)) |
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience'] | Python - Add Space between Potential Words
# Python3 code to demonstrate working of
# Add Space between Potential Words
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
res = []
for i in test_list:
for j in i:
if j.isupper():
i = i.replace(j, " " + j)
res.append(i)
# printing result
print("The space added list of strings : " + str(res))
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
[END] |
Python - Add Space between Potential Words | https://www.geeksforgeeks.org/python-add-space-between-potential-words/ | # Python3 code to demonstrate working of
# Add Space between Potential Words
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
res = []
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in test_list:
s = ""
for j in i:
if j in alphabets:
s += " " + j
else:
s += j
res.append(s)
# printing result
print("The space added list of strings : " + str(res)) |
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience'] | Python - Add Space between Potential Words
# Python3 code to demonstrate working of
# Add Space between Potential Words
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
res = []
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in test_list:
s = ""
for j in i:
if j in alphabets:
s += " " + j
else:
s += j
res.append(s)
# printing result
print("The space added list of strings : " + str(res))
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
[END] |
Python - Add Space between Potential Words | https://www.geeksforgeeks.org/python-add-space-between-potential-words/ | import re
def add_space(strings):
return [re.sub(r"([A-Z][a-z]+)", r" \1", ele) for ele in strings]
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
result = add_space(test_list)
print("The space added list of strings:", result)
# This code is contributed by Jyothi pinjala |
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience'] | Python - Add Space between Potential Words
import re
def add_space(strings):
return [re.sub(r"([A-Z][a-z]+)", r" \1", ele) for ele in strings]
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
result = add_space(test_list)
print("The space added list of strings:", result)
# This code is contributed by Jyothi pinjala
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
[END] |
Python - Add Space between Potential Words | https://www.geeksforgeeks.org/python-add-space-between-potential-words/ | import re
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
# define regular expression pattern
pattern = r"[A-Z]+[a-z]+[^a-zA-Z]*"
# define function to add spaces using regex
def add_space_regex(s):
return re.sub(pattern, r" \g<0>", s).strip()
# apply function to each element of the list using list comprehension
res = [add_space_regex(s) for s in test_list]
# printing result
print("The space added list of strings : " + str(res)) |
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience'] | Python - Add Space between Potential Words
import re
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
# define regular expression pattern
pattern = r"[A-Z]+[a-z]+[^a-zA-Z]*"
# define function to add spaces using regex
def add_space_regex(s):
return re.sub(pattern, r" \g<0>", s).strip()
# apply function to each element of the list using list comprehension
res = [add_space_regex(s) for s in test_list]
# printing result
print("The space added list of strings : " + str(res))
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
[END] |
Python - Add Space between Potential Words | https://www.geeksforgeeks.org/python-add-space-between-potential-words/ | from collections import defaultdict
original_list = ["gfgBest", "forGeeks", "andComputerScience"]
modified_list = []
for word in original_list:
d = defaultdict(str)
for i, c in enumerate(word):
if c.isupper():
d[i] += " "
d[i] += c
modified_list.append("".join(d.values()))
print("The modified list:", modified_list) |
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience'] | Python - Add Space between Potential Words
from collections import defaultdict
original_list = ["gfgBest", "forGeeks", "andComputerScience"]
modified_list = []
for word in original_list:
d = defaultdict(str)
for i, c in enumerate(word):
if c.isupper():
d[i] += " "
d[i] += c
modified_list.append("".join(d.values()))
print("The modified list:", modified_list)
#Output : The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
[END] |
Python - Filter the List of String whose index in second List contains the given Substring | https://www.geeksforgeeks.org/python-filter-the-list-of-string-whose-index-in-second-list-contaons-the-given-substring/ | # Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using zip() + loop + in
# operator
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
res = []
# using zip() to map by index
for ele1, ele2 in zip(test_list1, test_list2):
# checking for substring
if sub_str in ele2:
res.append(ele1)
# printing result
print("The extracted list : " + str(res)) |
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS'] | Python - Filter the List of String whose index in second List contains the given Substring
# Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using zip() + loop + in
# operator
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
res = []
# using zip() to map by index
for ele1, ele2 in zip(test_list1, test_list2):
# checking for substring
if sub_str in ele2:
res.append(ele1)
# printing result
print("The extracted list : " + str(res))
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS']
[END] |
Python - Filter the List of String whose index in second List contains the given Substring | https://www.geeksforgeeks.org/python-filter-the-list-of-string-whose-index-in-second-list-contaons-the-given-substring/ | # Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using list comprehension + zip()
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "no", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
# using list comprehension to perform task
res = [ele1 for ele1, ele2 in zip(test_list1, test_list2) if sub_str in ele2]
# printing result
print("The extracted list : " + str(res)) |
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS'] | Python - Filter the List of String whose index in second List contains the given Substring
# Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using list comprehension + zip()
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "no", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
# using list comprehension to perform task
res = [ele1 for ele1, ele2 in zip(test_list1, test_list2) if sub_str in ele2]
# printing result
print("The extracted list : " + str(res))
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS']
[END] |
Python - Filter the List of String whose index in second List contains the given Substring | https://www.geeksforgeeks.org/python-filter-the-list-of-string-whose-index-in-second-list-contaons-the-given-substring/ | # Python3 code to demonstrate working of
# Extract elements filtered by substring
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
res = []
for i in range(0, len(test_list2)):
if test_list2[i].find(sub_str) != -1:
res.append(test_list1[i])
# printing result
print("The extracted list : " + str(res)) |
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS'] | Python - Filter the List of String whose index in second List contains the given Substring
# Python3 code to demonstrate working of
# Extract elements filtered by substring
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
res = []
for i in range(0, len(test_list2)):
if test_list2[i].find(sub_str) != -1:
res.append(test_list1[i])
# printing result
print("The extracted list : " + str(res))
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS']
[END] |
Python - Filter the List of String whose index in second List contains the given Substring | https://www.geeksforgeeks.org/python-filter-the-list-of-string-whose-index-in-second-list-contaons-the-given-substring/ | # Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list using filter() function
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
# using filter() function to filter elements
res = list(filter(lambda x: sub_str in test_list2[test_list1.index(x)], test_list1))
# printing result
print("The extracted list : " + str(res)) |
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS'] | Python - Filter the List of String whose index in second List contains the given Substring
# Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list using filter() function
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
# using filter() function to filter elements
res = list(filter(lambda x: sub_str in test_list2[test_list1.index(x)], test_list1))
# printing result
print("The extracted list : " + str(res))
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS']
[END] |
Python - Filter the List of String whose index in second List contains the given Substring | https://www.geeksforgeeks.org/python-filter-the-list-of-string-whose-index-in-second-list-contaons-the-given-substring/ | # Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using itertools.compress()
import itertools
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
# using compress() to filter corresponding elements from test_list1
filtered_list = itertools.compress(test_list1, [sub_str in ele for ele in test_list2])
# converting filter object to list
res = list(filtered_list)
# printing result
print("The extracted list : " + str(res)) |
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS'] | Python - Filter the List of String whose index in second List contains the given Substring
# Python3 code to demonstrate working of
# Extract elements filtered by substring
# from other list Using itertools.compress()
import itertools
# initializing list
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# initializing substr
sub_str = "ok"
# using compress() to filter corresponding elements from test_list1
filtered_list = itertools.compress(test_list1, [sub_str in ele for ele in test_list2])
# converting filter object to list
res = list(filtered_list)
# printing result
print("The extracted list : " + str(res))
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS']
[END] |
Python - Filter the List of String whose index in second List contains the given Substring | https://www.geeksforgeeks.org/python-filter-the-list-of-string-whose-index-in-second-list-contaons-the-given-substring/ | test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
sub_str = "ok"
res = list(filter(lambda x: x[1].find(sub_str) != -1, zip(test_list1, test_list2)))
extracted_list = list(map(lambda x: x[0], res))
print("The extracted list : " + str(extracted_list)) |
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS'] | Python - Filter the List of String whose index in second List contains the given Substring
test_list1 = ["Gfg", "is", "not", "best", "and", "not", "for", "CS"]
test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "ok", "thats ok"]
sub_str = "ok"
res = list(filter(lambda x: x[1].find(sub_str) != -1, zip(test_list1, test_list2)))
extracted_list = list(map(lambda x: x[0], res))
print("The extracted list : " + str(extracted_list))
#Output : The original list 1 is : ['Gfg', 'is', 'not', 'best', 'and', 'not', 'for', 'CS']
[END] |
Python | Convert Character Matrix Rowix to single String | https://www.geeksforgeeks.org/python-convert-character-matrix-to-single-string/ | # Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using join() + list comprehension
# initializing list
test_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using join() + list comprehension
res = "".join(ele for sub in test_list for ele in sub)
# printing result
print("The String after join : " + res) |
#Output : The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] | Python | Convert Character Matrix Rowix to single String
# Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using join() + list comprehension
# initializing list
test_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using join() + list comprehension
res = "".join(ele for sub in test_list for ele in sub)
# printing result
print("The String after join : " + res)
#Output : The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
[END] |
Python | Convert Character Matrix Rowix to single String | https://www.geeksforgeeks.org/python-convert-character-matrix-to-single-string/ | # Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using join() + chain()
from itertools import chain
# Initializing list
test_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]]
# Printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using join() + chain()
res = "".join(chain(*test_list))
# Printing result
print("The String after join : " + res) |
#Output : The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] | Python | Convert Character Matrix Rowix to single String
# Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using join() + chain()
from itertools import chain
# Initializing list
test_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]]
# Printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using join() + chain()
res = "".join(chain(*test_list))
# Printing result
print("The String after join : " + res)
#Output : The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
[END] |
Python | Convert Character Matrix Rowix to single String | https://www.geeksforgeeks.org/python-convert-character-matrix-to-single-string/ | # Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using sum() + map()
# initializing list
test_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using sum() + map()
res = "".join(sum(map(list, test_list), []))
# printing result
print("The String after join : " + res) |
#Output : The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] | Python | Convert Character Matrix Rowix to single String
# Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using sum() + map()
# initializing list
test_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using sum() + map()
res = "".join(sum(map(list, test_list), []))
# printing result
print("The String after join : " + res)
#Output : The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
[END] |
Python | Convert Character Matrix Rowix to single String | https://www.geeksforgeeks.org/python-convert-character-matrix-to-single-string/ | # Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using reduce()
from functools import reduce
# initializing list
test_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using reduce()
res = reduce(lambda x, y: x + y, [char for row in test_list for char in row])
# printing result
print("The String after join : " + res) |
#Output : The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']] | Python | Convert Character Matrix Rowix to single String
# Python3 code to demonstrate working of
# Convert Character Matrix to single String
# Using reduce()
from functools import reduce
# initializing list
test_list = [["g", "f", "g"], ["i", "s"], ["b", "e", "s", "t"]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Character Matrix to single String
# Using reduce()
res = reduce(lambda x, y: x + y, [char for row in test_list for char in row])
# printing result
print("The String after join : " + res)
#Output : The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
[END] |
Python - Count String Lists with substring String List | https://www.geeksforgeeks.org/python-count-strings-with-substring-string-list/?ref=leftbar-rightbar | # Python code to demonstrate
# Count Strings with substring String List
# using list comprehension + len()
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# using list comprehension + len()
# Count Strings with substring String List
res = len([i for i in test_list if subs in i])
# printing result
print("All strings count with given substring are : " + str(res)) |
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] | Python - Count String Lists with substring String List
# Python code to demonstrate
# Count Strings with substring String List
# using list comprehension + len()
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# using list comprehension + len()
# Count Strings with substring String List
res = len([i for i in test_list if subs in i])
# printing result
print("All strings count with given substring are : " + str(res))
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
[END] |
Python - Count String Lists with substring String List | https://www.geeksforgeeks.org/python-count-strings-with-substring-string-list/?ref=leftbar-rightbar | # Python code to demonstrate
# Count Strings with substring String List
# using filter() + lambda + len()
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# using filter() + lambda + len()
# Count Strings with substring String List
res = len(list(filter(lambda x: subs in x, test_list)))
# printing result
print("All strings count with given substring are : " + str(res)) |
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] | Python - Count String Lists with substring String List
# Python code to demonstrate
# Count Strings with substring String List
# using filter() + lambda + len()
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# using filter() + lambda + len()
# Count Strings with substring String List
res = len(list(filter(lambda x: subs in x, test_list)))
# printing result
print("All strings count with given substring are : " + str(res))
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
[END] |
Python - Count String Lists with substring String List | https://www.geeksforgeeks.org/python-count-strings-with-substring-string-list/?ref=leftbar-rightbar | # Python code to demonstrate
# Count Strings with substring String List
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# Count Strings with substring String List
res = 0
for i in test_list:
if i.find(subs) != -1:
res += 1
# printing result
print("All strings count with given substring are : " + str(res)) |
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] | Python - Count String Lists with substring String List
# Python code to demonstrate
# Count Strings with substring String List
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# Count Strings with substring String List
res = 0
for i in test_list:
if i.find(subs) != -1:
res += 1
# printing result
print("All strings count with given substring are : " + str(res))
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
[END] |
Python - Count String Lists with substring String List | https://www.geeksforgeeks.org/python-count-strings-with-substring-string-list/?ref=leftbar-rightbar | # Python code to demonstrate
# Count Strings with substring String List
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# Count Strings with substring String List
res = 0
import operator
for i in test_list:
if operator.contains(i, subs):
res += 1
# printing result
print("All strings count with given substring are : " + str(res)) |
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] | Python - Count String Lists with substring String List
# Python code to demonstrate
# Count Strings with substring String List
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# Count Strings with substring String List
res = 0
import operator
for i in test_list:
if operator.contains(i, subs):
res += 1
# printing result
print("All strings count with given substring are : " + str(res))
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
[END] |
Python - Count String Lists with substring String List | https://www.geeksforgeeks.org/python-count-strings-with-substring-string-list/?ref=leftbar-rightbar | # Python code to demonstrate
# Count Strings with substring String List
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# Count Strings with substring String List
res = sum(1 for s in test_list if s.count(subs) > 0)
# printing result
print("All strings count with given substring are : " + str(res)) |
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] | Python - Count String Lists with substring String List
# Python code to demonstrate
# Count Strings with substring String List
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is : " + str(test_list))
# initializing substring
subs = "Geek"
# Count Strings with substring String List
res = sum(1 for s in test_list if s.count(subs) > 0)
# printing result
print("All strings count with given substring are : " + str(res))
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
[END] |
Python - Count String Lists with substring String List | https://www.geeksforgeeks.org/python-count-strings-with-substring-string-list/?ref=leftbar-rightbar | from functools import reduce
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
subs = "Geek"
# printing original list
print("The original list is : " + str(test_list))
count = reduce(lambda x, y: x + 1 if subs in y else x, test_list, 0)
# printing result
print("All strings count with given substring are :", count)
# This code is contributed by Jyothi pinjala. |
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] | Python - Count String Lists with substring String List
from functools import reduce
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
subs = "Geek"
# printing original list
print("The original list is : " + str(test_list))
count = reduce(lambda x, y: x + 1 if subs in y else x, test_list, 0)
# printing result
print("All strings count with given substring are :", count)
# This code is contributed by Jyothi pinjala.
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
[END] |
Python - Count String Lists with substring String List | https://www.geeksforgeeks.org/python-count-strings-with-substring-string-list/?ref=leftbar-rightbar | # Python code to demonstrate
# Count Strings with substring String List
# using for loop
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is: " + str(test_list))
# initializing substring
subs = "Geek"
# using for loop
count = 0
for string in test_list:
if subs in string:
count += 1
# printing result
print("All strings count with given substring are: " + str(count)) |
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms'] | Python - Count String Lists with substring String List
# Python code to demonstrate
# Count Strings with substring String List
# using for loop
# initializing list
test_list = ["GeeksforGeeks", "Geeky", "Computers", "Algorithms"]
# printing original list
print("The original list is: " + str(test_list))
# initializing substring
subs = "Geek"
# using for loop
count = 0
for string in test_list:
if subs in string:
count += 1
# printing result
print("All strings count with given substring are: " + str(count))
#Output : The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
[END] |
Python - Replace Substrings from String List | https://www.geeksforgeeks.org/python-replace-substrings-from-string-list/ | # Python3 code to demonstrate
# Replace Substrings from String List
# using loop + replace() + enumerate()
# Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List
# using loop + replace() + enumerate()
sub = dict(test_list2)
for key, val in sub.items():
for idx, ele in enumerate(test_list1):
if key in ele:
test_list1[idx] = ele.replace(key, val)
# printing result
print("The list after replacement : " + str(test_list1)) |
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science'] | Python - Replace Substrings from String List
# Python3 code to demonstrate
# Replace Substrings from String List
# using loop + replace() + enumerate()
# Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List
# using loop + replace() + enumerate()
sub = dict(test_list2)
for key, val in sub.items():
for idx, ele in enumerate(test_list1):
if key in ele:
test_list1[idx] = ele.replace(key, val)
# printing result
print("The list after replacement : " + str(test_list1))
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
[END] |
Python - Replace Substrings from String List | https://www.geeksforgeeks.org/python-replace-substrings-from-string-list/ | # Python3 code to demonstrate
# Replace Substrings from String List
# using replace() + list comprehension
# Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List
# using replace() + list comprehension
res = [
sub.replace(sub2[0], sub2[1])
for sub in test_list1
for sub2 in test_list2
if sub2[0] in sub
]
# printing result
print("The list after replacement : " + str(res)) |
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science'] | Python - Replace Substrings from String List
# Python3 code to demonstrate
# Replace Substrings from String List
# using replace() + list comprehension
# Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List
# using replace() + list comprehension
res = [
sub.replace(sub2[0], sub2[1])
for sub in test_list1
for sub2 in test_list2
if sub2[0] in sub
]
# printing result
print("The list after replacement : " + str(res))
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
[END] |
Python - Replace Substrings from String List | https://www.geeksforgeeks.org/python-replace-substrings-from-string-list/ | import re
# Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List using re module
for sub in test_list2:
test_list1 = [re.sub(sub[0], sub[1], ele) for ele in test_list1]
# printing result
print("The list after replacement : " + str(test_list1))
# This code is contributed by Edula Vinay Kumar Reddy |
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science'] | Python - Replace Substrings from String List
import re
# Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List using re module
for sub in test_list2:
test_list1 = [re.sub(sub[0], sub[1], ele) for ele in test_list1]
# printing result
print("The list after replacement : " + str(test_list1))
# This code is contributed by Edula Vinay Kumar Reddy
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
[END] |
Python - Replace Substrings from String List | https://www.geeksforgeeks.org/python-replace-substrings-from-string-list/ | # Python3 code to demonstrate
# Replace Substrings from String List
# using list comprehension + reduce() + replace() method
from functools import reduce
# Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List
# using list comprehension + reduce() + replace() method
sub = dict(test_list2)
res = [reduce(lambda i, j: i.replace(*j), sub.items(), ele) for ele in test_list1]
# printing result
print("The list after replacement : " + str(res)) |
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science'] | Python - Replace Substrings from String List
# Python3 code to demonstrate
# Replace Substrings from String List
# using list comprehension + reduce() + replace() method
from functools import reduce
# Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List
# using list comprehension + reduce() + replace() method
sub = dict(test_list2)
res = [reduce(lambda i, j: i.replace(*j), sub.items(), ele) for ele in test_list1]
# printing result
print("The list after replacement : " + str(res))
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
[END] |
Python - Replace Substrings from String List | https://www.geeksforgeeks.org/python-replace-substrings-from-string-list/ | # Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List
# using a loop, dictionary, and string methods
sub = {k: v for k, v in test_list2}
res = []
for ele in test_list1:
for key in sub:
ele = ele.replace(key, sub[key])
res.append(ele)
# printing result
print("The list after replacement : " + str(res))
# This code is contributed by Vinay Pinjala. |
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science'] | Python - Replace Substrings from String List
# Initializing list1
test_list1 = ["GeeksforGeeks", "is", "Best", "For", "Geeks", "And", "Computer Science"]
test_list2 = [["Geeks", "Gks"], ["And", "&"], ["Computer", "Comp"]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Replace Substrings from String List
# using a loop, dictionary, and string methods
sub = {k: v for k, v in test_list2}
res = []
for ele in test_list1:
for key in sub:
ele = ele.replace(key, sub[key])
res.append(ele)
# printing result
print("The list after replacement : " + str(res))
# This code is contributed by Vinay Pinjala.
#Output : The original list 1 is : ['GeeksforGeeks', 'is', 'Best', 'For', 'Geeks', 'And', 'Computer Science']
[END] |
Python - Group Sublists by another list | https://www.geeksforgeeks.org/python-group-sublists-by-another-list/ | # Python3 code to demonstrate
# Group Sublists by another List
# using loop + generator(yield)
# helper function
def grp_ele(test_list1, test_list2):
temp = []
for i in test_list1:
if i in test_list2:
if temp:
yield temp
temp = []
yield i
else:
temp.append(i)
if temp:
yield temp
# Initializing lists
test_list1 = [8, 5, 9, 11, 3, 7]
test_list2 = [9, 11]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Group Sublists by another List
# using loop + generator(yield)
res = list(grp_ele(test_list1, test_list2))
# printing result
print("The Grouped list is : " + str(res)) |
#Output : The original list 1 is : [8, 5, 9, 11, 3, 7] | Python - Group Sublists by another list
# Python3 code to demonstrate
# Group Sublists by another List
# using loop + generator(yield)
# helper function
def grp_ele(test_list1, test_list2):
temp = []
for i in test_list1:
if i in test_list2:
if temp:
yield temp
temp = []
yield i
else:
temp.append(i)
if temp:
yield temp
# Initializing lists
test_list1 = [8, 5, 9, 11, 3, 7]
test_list2 = [9, 11]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Group Sublists by another List
# using loop + generator(yield)
res = list(grp_ele(test_list1, test_list2))
# printing result
print("The Grouped list is : " + str(res))
#Output : The original list 1 is : [8, 5, 9, 11, 3, 7]
[END] |
Python | Remove Reduntant Substrings from String List | https://www.geeksforgeeks.org/python-remove-reduntant-substrings-from-strings-list/ | # Python3 code to demonstrate working of
# Remove Redundant Substrings from Strings List
# Using enumerate() + join() + sort()
# initializing list
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
# printing original list
print("The original list : " + str(test_list))
# using loop to iterate for each string
test_list.sort(key=len)
res = []
for idx, val in enumerate(test_list):
# concatenating all next values and checking for existence
if val not in ", ".join(test_list[idx + 1 :]):
res.append(val)
# printing result
print("The filtered list : " + str(res)) |
#Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] | Python | Remove Reduntant Substrings from String List
# Python3 code to demonstrate working of
# Remove Redundant Substrings from Strings List
# Using enumerate() + join() + sort()
# initializing list
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
# printing original list
print("The original list : " + str(test_list))
# using loop to iterate for each string
test_list.sort(key=len)
res = []
for idx, val in enumerate(test_list):
# concatenating all next values and checking for existence
if val not in ", ".join(test_list[idx + 1 :]):
res.append(val)
# printing result
print("The filtered list : " + str(res))
#Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks']
[END] |
Python | Remove Reduntant Substrings from String List | https://www.geeksforgeeks.org/python-remove-reduntant-substrings-from-strings-list/ | # Python3 code to demonstrate working of
# Remove Redundant Substrings from Strings List
# Using list comprehension + join() + enumerate()
# initializing list
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension to iterate for each string
# and perform join in one liner
test_list.sort(key=len)
res = [
val
for idx, val in enumerate(test_list)
if val not in ", ".join(test_list[idx + 1 :])
]
# printing result
print("The filtered list : " + str(res)) |
#Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] | Python | Remove Reduntant Substrings from String List
# Python3 code to demonstrate working of
# Remove Redundant Substrings from Strings List
# Using list comprehension + join() + enumerate()
# initializing list
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension to iterate for each string
# and perform join in one liner
test_list.sort(key=len)
res = [
val
for idx, val in enumerate(test_list)
if val not in ", ".join(test_list[idx + 1 :])
]
# printing result
print("The filtered list : " + str(res))
#Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks']
[END] |
Python | Remove Reduntant Substrings from String List | https://www.geeksforgeeks.org/python-remove-reduntant-substrings-from-strings-list/ | def remove_redundant_substrings(strings):
# Base case: if the list is empty or has only one element, return it
if len(strings) <= 1:
return strings
# Sort the list by length to simplify the recursion
strings.sort(key=len)
# Take the first string and remove it from the list
current_string = strings.pop(0)
# Recursively remove redundant substrings from the rest of the list
remaining_strings = remove_redundant_substrings(strings)
# Check if the current string is a redundant substring of any of the remaining strings
for string in remaining_strings:
if current_string in string:
return remaining_strings
# If the current string is not redundant, add it back to the list and return it
remaining_strings.append(current_string)
return remaining_strings
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
print("The original list : " + str(test_list))
res = remove_redundant_substrings(test_list)
print("The filtered list : " + str(res)) |
#Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] | Python | Remove Reduntant Substrings from String List
def remove_redundant_substrings(strings):
# Base case: if the list is empty or has only one element, return it
if len(strings) <= 1:
return strings
# Sort the list by length to simplify the recursion
strings.sort(key=len)
# Take the first string and remove it from the list
current_string = strings.pop(0)
# Recursively remove redundant substrings from the rest of the list
remaining_strings = remove_redundant_substrings(strings)
# Check if the current string is a redundant substring of any of the remaining strings
for string in remaining_strings:
if current_string in string:
return remaining_strings
# If the current string is not redundant, add it back to the list and return it
remaining_strings.append(current_string)
return remaining_strings
test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"]
print("The original list : " + str(test_list))
res = remove_redundant_substrings(test_list)
print("The filtered list : " + str(res))
#Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks']
[END] |
Python - Sort String by Custom Integer Substrings | https://www.geeksforgeeks.org/python-sort-string-by-custom-integer-substrings/ | # Python3 code to demonstrate working of
# Sort String by Custom Substrings
# Using sorted() + zip() + lambda + regex()
import re
# initializing list
test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"]
# printing original list
print("The original list : " + str(test_list))
# initializing substring list
subord_list = ["6", "7", "4", "11"]
# creating inverse mapping with index
temp_dict = {val: key for key, val in enumerate(subord_list)}
# custom sorting
temp_list = sorted(
[[ele, temp_dict[re.search("(\d+)$", ele).group()]] for ele in test_list],
key=lambda x: x[1],
)
# compiling result
res = [ele for ele in list(zip(*temp_list))[0]]
# printing result
print("The sorted list : " + str(res)) |
#Output : The original list : ['Good at 4', 'Wake at 7', 'Work till 6', 'Sleep at 11'] | Python - Sort String by Custom Integer Substrings
# Python3 code to demonstrate working of
# Sort String by Custom Substrings
# Using sorted() + zip() + lambda + regex()
import re
# initializing list
test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"]
# printing original list
print("The original list : " + str(test_list))
# initializing substring list
subord_list = ["6", "7", "4", "11"]
# creating inverse mapping with index
temp_dict = {val: key for key, val in enumerate(subord_list)}
# custom sorting
temp_list = sorted(
[[ele, temp_dict[re.search("(\d+)$", ele).group()]] for ele in test_list],
key=lambda x: x[1],
)
# compiling result
res = [ele for ele in list(zip(*temp_list))[0]]
# printing result
print("The sorted list : " + str(res))
#Output : The original list : ['Good at 4', 'Wake at 7', 'Work till 6', 'Sleep at 11']
[END] |
Python - Sort String by Custom Integer Substrings | https://www.geeksforgeeks.org/python-sort-string-by-custom-integer-substrings/ | # Python3 code to demonstrate working of
# Sort String by Custom Substrings
# Using sorted() + comparator + regex()
import re
# helper function to solve problem
def hlper_fnc(ele):
temp = re.search("(\d+)$", ele).group()
return temp_dict[temp] if temp in temp_dict else int(temp)
# initializing list
test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"]
# printing original list
print("The original list : " + str(test_list))
# initializing substring list
subord_list = ["6", "7", "4", "11"]
# creating inverse mapping with index
temp_dict = {val: key for key, val in enumerate(test_list)}
# sorting using comparator
test_list.sort(key=lambda ele: hlper_fnc(ele))
# printing result
print("The sorted list : " + str(test_list)) |
#Output : The original list : ['Good at 4', 'Wake at 7', 'Work till 6', 'Sleep at 11'] | Python - Sort String by Custom Integer Substrings
# Python3 code to demonstrate working of
# Sort String by Custom Substrings
# Using sorted() + comparator + regex()
import re
# helper function to solve problem
def hlper_fnc(ele):
temp = re.search("(\d+)$", ele).group()
return temp_dict[temp] if temp in temp_dict else int(temp)
# initializing list
test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"]
# printing original list
print("The original list : " + str(test_list))
# initializing substring list
subord_list = ["6", "7", "4", "11"]
# creating inverse mapping with index
temp_dict = {val: key for key, val in enumerate(test_list)}
# sorting using comparator
test_list.sort(key=lambda ele: hlper_fnc(ele))
# printing result
print("The sorted list : " + str(test_list))
#Output : The original list : ['Good at 4', 'Wake at 7', 'Work till 6', 'Sleep at 11']
[END] |
Python - Sort String by Custom Integer Substrings | https://www.geeksforgeeks.org/python-sort-string-by-custom-integer-substrings/ | # Python3 code to demonstrate working of
# Sort String by Custom Substrings
# Using dictionary and sorted()
import re
# initializing list
test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"]
# printing original list
print("The original list : " + str(test_list))
# initializing substring list
subord_list = ["6", "7", "4", "11"]
# creating dictionary to store mappings of substrings to orders
order_dict = {}
for i in range(len(subord_list)):
order_dict[subord_list[i]] = i
# sorting based on the values of the mappings using sorted()
test_list = sorted(test_list, key=lambda x: order_dict[re.search("(\d+)$", x).group()])
# printing result
print("The sorted list : " + str(test_list)) |
#Output : The original list : ['Good at 4', 'Wake at 7', 'Work till 6', 'Sleep at 11'] | Python - Sort String by Custom Integer Substrings
# Python3 code to demonstrate working of
# Sort String by Custom Substrings
# Using dictionary and sorted()
import re
# initializing list
test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"]
# printing original list
print("The original list : " + str(test_list))
# initializing substring list
subord_list = ["6", "7", "4", "11"]
# creating dictionary to store mappings of substrings to orders
order_dict = {}
for i in range(len(subord_list)):
order_dict[subord_list[i]] = i
# sorting based on the values of the mappings using sorted()
test_list = sorted(test_list, key=lambda x: order_dict[re.search("(\d+)$", x).group()])
# printing result
print("The sorted list : " + str(test_list))
#Output : The original list : ['Good at 4', 'Wake at 7', 'Work till 6', 'Sleep at 11']
[END] |
Python - Test if Substring occurs in specific position | https://www.geeksforgeeks.org/python-test-if-substring-occurs-in-specific-position/ | # Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# Using loop
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using loop
res = True
k = 0
for idx in range(len(test_str)):
if idx >= i and idx < j:
if test_str[idx] != substr[k]:
res = False
break
k = k + 1
# printing result
print("Does string contain substring at required position ? : " + str(res)) |
#Output : The original string is : Gfg is best | Python - Test if Substring occurs in specific position
# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# Using loop
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using loop
res = True
k = 0
for idx in range(len(test_str)):
if idx >= i and idx < j:
if test_str[idx] != substr[k]:
res = False
break
k = k + 1
# printing result
print("Does string contain substring at required position ? : " + str(res))
#Output : The original string is : Gfg is best
[END] |
Python - Test if Substring occurs in specific position | https://www.geeksforgeeks.org/python-test-if-substring-occurs-in-specific-position/ | # Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# Using string slicing
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using string slicing
res = test_str[i:j] == substr
# printing result
print("Does string contain substring at required position ? : " + str(res)) |
#Output : The original string is : Gfg is best | Python - Test if Substring occurs in specific position
# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# Using string slicing
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using string slicing
res = test_str[i:j] == substr
# printing result
print("Does string contain substring at required position ? : " + str(res))
#Output : The original string is : Gfg is best
[END] |
Python - Test if Substring occurs in specific position | https://www.geeksforgeeks.org/python-test-if-substring-occurs-in-specific-position/ | # Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using string slicing
res = False
if test_str.find(substr) == i:
res = True
# printing result
print("Does string contain substring at required position ? : " + str(res)) |
#Output : The original string is : Gfg is best | Python - Test if Substring occurs in specific position
# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using string slicing
res = False
if test_str.find(substr) == i:
res = True
# printing result
print("Does string contain substring at required position ? : " + str(res))
#Output : The original string is : Gfg is best
[END] |
Python - Test if Substring occurs in specific position | https://www.geeksforgeeks.org/python-test-if-substring-occurs-in-specific-position/ | # Python3 code to demonstrate working of
# Test if Substring occurs in specific position
def substring_occurs_at_position(test_str, substr, i, j):
if j > len(test_str):
return False
if test_str[i:j] == substr:
return True
return substring_occurs_at_position(test_str, substr, i + 1, j + 1)
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
result = substring_occurs_at_position(test_str, substr, i, j)
# printing result
print("Does string contain substring at required position? ", result)
# this code contributed by tvsk |
#Output : The original string is : Gfg is best | Python - Test if Substring occurs in specific position
# Python3 code to demonstrate working of
# Test if Substring occurs in specific position
def substring_occurs_at_position(test_str, substr, i, j):
if j > len(test_str):
return False
if test_str[i:j] == substr:
return True
return substring_occurs_at_position(test_str, substr, i + 1, j + 1)
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
result = substring_occurs_at_position(test_str, substr, i, j)
# printing result
print("Does string contain substring at required position? ", result)
# this code contributed by tvsk
#Output : The original string is : Gfg is best
[END] |
Python - Test if Substring occurs in specific position | https://www.geeksforgeeks.org/python-test-if-substring-occurs-in-specific-position/ | import re
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using regular expression
pattern = "^" + substr + "$"
res = bool(re.search(pattern, test_str[i : j + 1]))
# printing result
print("Does string contain substring at required position ? : " + str(res)) |
#Output : The original string is : Gfg is best | Python - Test if Substring occurs in specific position
import re
# initializing string
test_str = "Gfg is best"
# printing original string
print("The original string is : " + test_str)
# initializing range
i, j = 7, 11
# initializing substr
substr = "best"
# Test if Substring occurs in specific position
# Using regular expression
pattern = "^" + substr + "$"
res = bool(re.search(pattern, test_str[i : j + 1]))
# printing result
print("Does string contain substring at required position ? : " + str(res))
#Output : The original string is : Gfg is best
[END] |
Python program to check whether the string is Symmetrical or Palindrome | https://www.geeksforgeeks.org/python-program-to-check-whether-the-string-is-symmetrical-or-palindrome/?ref=leftbar-rightbar | # Python program to demonstrate
# symmetry and palindrome of the
# string
# Function to check whether the
# string is palindrome or not
def palindrome(a):
# finding the mid, start
# and last index of the string
mid = (len(a) - 1) // 2 # you can remove the -1 or you add <= sign in line 21
start = 0 # so that you can compare the middle elements also.
last = len(a) - 1
flag = 0
# A loop till the mid of the
# string
while start <= mid:
# comparing letters from right
# from the letters from left
if a[start] == a[last]:
start += 1
last -= 1
else:
flag = 1
break
# Checking the flag variable to
# check if the string is palindrome
# or not
if flag == 0:
print("The entered string is palindrome")
else:
print("The entered string is not palindrome")
# Function to check whether the
# string is symmetrical or not
def symmetry(a):
n = len(a)
flag = 0
# Check if the string's length
# is odd or even
if n % 2:
mid = n // 2 + 1
else:
mid = n // 2
start1 = 0
start2 = mid
while start1 < mid and start2 < n:
if a[start1] == a[start2]:
start1 = start1 + 1
start2 = start2 + 1
else:
flag = 1
break
# Checking the flag variable to
# check if the string is symmetrical
# or not
if flag == 0:
print("The entered string is symmetrical")
else:
print("The entered string is not symmetrical")
# Driver code
string = "amaama"
palindrome(string)
symmetry(string) | Input: khokho
Output: | Python program to check whether the string is Symmetrical or Palindrome
# Python program to demonstrate
# symmetry and palindrome of the
# string
# Function to check whether the
# string is palindrome or not
def palindrome(a):
# finding the mid, start
# and last index of the string
mid = (len(a) - 1) // 2 # you can remove the -1 or you add <= sign in line 21
start = 0 # so that you can compare the middle elements also.
last = len(a) - 1
flag = 0
# A loop till the mid of the
# string
while start <= mid:
# comparing letters from right
# from the letters from left
if a[start] == a[last]:
start += 1
last -= 1
else:
flag = 1
break
# Checking the flag variable to
# check if the string is palindrome
# or not
if flag == 0:
print("The entered string is palindrome")
else:
print("The entered string is not palindrome")
# Function to check whether the
# string is symmetrical or not
def symmetry(a):
n = len(a)
flag = 0
# Check if the string's length
# is odd or even
if n % 2:
mid = n // 2 + 1
else:
mid = n // 2
start1 = 0
start2 = mid
while start1 < mid and start2 < n:
if a[start1] == a[start2]:
start1 = start1 + 1
start2 = start2 + 1
else:
flag = 1
break
# Checking the flag variable to
# check if the string is symmetrical
# or not
if flag == 0:
print("The entered string is symmetrical")
else:
print("The entered string is not symmetrical")
# Driver code
string = "amaama"
palindrome(string)
symmetry(string)
Input: khokho
Output:
[END] |
Python program to check whether the string is Symmetrical or Palindrome | https://www.geeksforgeeks.org/python-program-to-check-whether-the-string-is-symmetrical-or-palindrome/?ref=leftbar-rightbar | string = "amaama"
half = int(len(string) / 2)
first_str = string[:half]
second_str = string[half:]
# symmetric
if first_str == second_str:
print(string, "string is symmetrical")
else:
print(string, "string is not symmetrical")
# palindrome
if first_str == second_str[::-1]: # ''.join(reversed(second_str)) [slower]
print(string, "string is palindrome")
else:
print(string, "string is not palindrome") | Input: khokho
Output: | Python program to check whether the string is Symmetrical or Palindrome
string = "amaama"
half = int(len(string) / 2)
first_str = string[:half]
second_str = string[half:]
# symmetric
if first_str == second_str:
print(string, "string is symmetrical")
else:
print(string, "string is not symmetrical")
# palindrome
if first_str == second_str[::-1]: # ''.join(reversed(second_str)) [slower]
print(string, "string is palindrome")
else:
print(string, "string is not palindrome")
Input: khokho
Output:
[END] |
Python program to check whether the string is Symmetrical or Palindrome | https://www.geeksforgeeks.org/python-program-to-check-whether-the-string-is-symmetrical-or-palindrome/?ref=leftbar-rightbar | # Python program to check whether the string is Symmetrical or Palindrome
import re
input_str = "amaama"
reversed_str = input_str[::-1]
if input_str == reversed_str:
print("The entered string is symmetrical")
else:
print("The entered string is not symmetrical")
if re.match("^(\w+)\Z", input_str) and input_str == input_str[::-1]:
print("The entered string is palindrome")
else:
print("The entered string is not palindrome") | Input: khokho
Output: | Python program to check whether the string is Symmetrical or Palindrome
# Python program to check whether the string is Symmetrical or Palindrome
import re
input_str = "amaama"
reversed_str = input_str[::-1]
if input_str == reversed_str:
print("The entered string is symmetrical")
else:
print("The entered string is not symmetrical")
if re.match("^(\w+)\Z", input_str) and input_str == input_str[::-1]:
print("The entered string is palindrome")
else:
print("The entered string is not palindrome")
Input: khokho
Output:
[END] |
Reverse words in a given String in Python | https://www.geeksforgeeks.org/reverse-words-given-string-python/ | # Python code
# To reverse words in a given string
# input string
string = "geeks quiz practice code"
# reversing words in a given string
s = string.split()[::-1]
l = []
for i in s:
# appending reversed words to l
l.append(i)
# printing reverse words
print(" ".join(l)) | #Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks??? | Reverse words in a given String in Python
# Python code
# To reverse words in a given string
# input string
string = "geeks quiz practice code"
# reversing words in a given string
s = string.split()[::-1]
l = []
for i in s:
# appending reversed words to l
l.append(i)
# printing reverse words
print(" ".join(l))
#Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks???
[END] |
Reverse words in a given String in Python | https://www.geeksforgeeks.org/reverse-words-given-string-python/ | # Function to reverse words of string
def rev_sentence(sentence):
# first split the string into words
words = sentence.split(" ")
# then reverse the split string list and join using space
reverse_sentence = " ".join(reversed(words))
# finally return the joined string
return reverse_sentence
if __name__ == "__main__":
input = "geeks quiz practice code"
print(rev_sentence(input)) | #Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks??? | Reverse words in a given String in Python
# Function to reverse words of string
def rev_sentence(sentence):
# first split the string into words
words = sentence.split(" ")
# then reverse the split string list and join using space
reverse_sentence = " ".join(reversed(words))
# finally return the joined string
return reverse_sentence
if __name__ == "__main__":
input = "geeks quiz practice code"
print(rev_sentence(input))
#Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks???
[END] |
Reverse words in a given String in Python | https://www.geeksforgeeks.org/reverse-words-given-string-python/ | # Function to reverse words of string
import re
def rev_sentence(sentence):
# find all the words in sentence
words = re.findall("\w+", sentence)
# Backward iterate over list of words and join using space
reverse_sentence = " ".join(words[i] for i in range(len(words) - 1, -1, -1))
# finally return the joined string
return reverse_sentence
if __name__ == "__main__":
input = "geeks quiz practice code"
print(rev_sentence(input)) | #Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks??? | Reverse words in a given String in Python
# Function to reverse words of string
import re
def rev_sentence(sentence):
# find all the words in sentence
words = re.findall("\w+", sentence)
# Backward iterate over list of words and join using space
reverse_sentence = " ".join(words[i] for i in range(len(words) - 1, -1, -1))
# finally return the joined string
return reverse_sentence
if __name__ == "__main__":
input = "geeks quiz practice code"
print(rev_sentence(input))
#Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks???
[END] |
Reverse words in a given String in Python | https://www.geeksforgeeks.org/reverse-words-given-string-python/ | # initializing string
string = "geeks quiz practice code"
# creating an empty stack
stack = []
# pushing words onto the stack
for word in string.split():
stack.append(word)
# creating an empty list to store the reversed words
reversed_words = []
# popping words off the stack and appending them to the list
while stack:
reversed_words.append(stack.pop())
# joining the reversed words with a space
reversed_string = " ".join(reversed_words)
# printing the reversed string
print(reversed_string)
# This code is contributed by Edula Vinay Kumar Reddy | #Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks??? | Reverse words in a given String in Python
# initializing string
string = "geeks quiz practice code"
# creating an empty stack
stack = []
# pushing words onto the stack
for word in string.split():
stack.append(word)
# creating an empty list to store the reversed words
reversed_words = []
# popping words off the stack and appending them to the list
while stack:
reversed_words.append(stack.pop())
# joining the reversed words with a space
reversed_string = " ".join(reversed_words)
# printing the reversed string
print(reversed_string)
# This code is contributed by Edula Vinay Kumar Reddy
#Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks???
[END] |
Reverse words in a given String in Python | https://www.geeksforgeeks.org/reverse-words-given-string-python/ | def reverse_words(string):
# split the string into a list of words
words = string.split()
# initialize an empty string to store the reversed words
reversed_string = ""
# loop through the words in reverse order and append them to the reversed string
for i in range(len(words) - 1, -1, -1):
reversed_string += words[i] + " "
# remove the extra space at the end of the reversed string and return it
return reversed_string.strip()
# example usage
string = "geeks quiz practice code"
reversed_string = reverse_words(string)
print(reversed_string) # output: "code practice quiz geeks" | #Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks??? | Reverse words in a given String in Python
def reverse_words(string):
# split the string into a list of words
words = string.split()
# initialize an empty string to store the reversed words
reversed_string = ""
# loop through the words in reverse order and append them to the reversed string
for i in range(len(words) - 1, -1, -1):
reversed_string += words[i] + " "
# remove the extra space at the end of the reversed string and return it
return reversed_string.strip()
# example usage
string = "geeks quiz practice code"
reversed_string = reverse_words(string)
print(reversed_string) # output: "code practice quiz geeks"
#Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks???
[END] |
Reverse words in a given String in Python | https://www.geeksforgeeks.org/reverse-words-given-string-python/ | # Python program for the above approach
# Function to reverse the words in string
def reverse_word(s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
# Function to reverse the string
def reverse_string(s):
s = list(s)
start, end = 0, len(s) - 1
reverse_word(s, start, end)
start = end = 0
# Iterate over the string S
while end < len(s):
if s[end] == " ":
reverse_word(s, start, end - 1)
start = end + 1
end += 1
# Reverse the words
reverse_word(s, start, end - 1)
return "".join(s)
# Driver Code
S = "geeks quiz practice code"
print(reverse_string(S)) | #Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks??? | Reverse words in a given String in Python
# Python program for the above approach
# Function to reverse the words in string
def reverse_word(s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
# Function to reverse the string
def reverse_string(s):
s = list(s)
start, end = 0, len(s) - 1
reverse_word(s, start, end)
start = end = 0
# Iterate over the string S
while end < len(s):
if s[end] == " ":
reverse_word(s, start, end - 1)
start = end + 1
end += 1
# Reverse the words
reverse_word(s, start, end - 1)
return "".join(s)
# Driver Code
S = "geeks quiz practice code"
print(reverse_string(S))
#Input : str =" geeks quiz practice code"
#Output : str = code practice quiz geeks???
[END] |
Ways to remove i - th character from string in python | https://www.geeksforgeeks.org/ways-to-remove-ith-character-from-string-in-python/ | test_str = "GeeksForGeeks"
# Removing char at pos 3
new_str = ""
for i in range(len(test_str)):
if i != 2:
new_str = new_str + test_str[i]
# Printing string after removal
print("The string after removal of i'th character : " + new_str) |
#Output : The string after removal of i'th character : GeksForGeeks | Ways to remove i - th character from string in python
test_str = "GeeksForGeeks"
# Removing char at pos 3
new_str = ""
for i in range(len(test_str)):
if i != 2:
new_str = new_str + test_str[i]
# Printing string after removal
print("The string after removal of i'th character : " + new_str)
#Output : The string after removal of i'th character : GeksForGeeks
[END] |
Ways to remove i - th character from string in python | https://www.geeksforgeeks.org/ways-to-remove-ith-character-from-string-in-python/ | # Initializing String
test_str = "GeeksForGeeks"
# Removing char at pos 3
# using replace
new_str = test_str.replace("e", "")
# Printing string after removal
# removes all occurrences of 'e'
print("The string after removal of i'th character( doesn't work) : " + new_str)
# Removing 1st occurrence of s, i.e 5th pos.
# if we wish to remove it.
new_str = test_str.replace("s", "", 1)
# Printing string after removal
# removes first occurrences of s
print("The string after removal of i'th character(works) : " + new_str) |
#Output : The string after removal of i'th character : GeksForGeeks | Ways to remove i - th character from string in python
# Initializing String
test_str = "GeeksForGeeks"
# Removing char at pos 3
# using replace
new_str = test_str.replace("e", "")
# Printing string after removal
# removes all occurrences of 'e'
print("The string after removal of i'th character( doesn't work) : " + new_str)
# Removing 1st occurrence of s, i.e 5th pos.
# if we wish to remove it.
new_str = test_str.replace("s", "", 1)
# Printing string after removal
# removes first occurrences of s
print("The string after removal of i'th character(works) : " + new_str)
#Output : The string after removal of i'th character : GeksForGeeks
[END] |
Ways to remove i - th character from string in python | https://www.geeksforgeeks.org/ways-to-remove-ith-character-from-string-in-python/ | # Initializing String
test_str = "GeeksForGeeks"
# Removing char at pos 3
# using slice + concatenation
new_str = test_str[:2] + test_str[3:]
# Printing string after removal
# removes ele. at 3rd index
print("The string after removal of i'th character : " + new_str) |
#Output : The string after removal of i'th character : GeksForGeeks | Ways to remove i - th character from string in python
# Initializing String
test_str = "GeeksForGeeks"
# Removing char at pos 3
# using slice + concatenation
new_str = test_str[:2] + test_str[3:]
# Printing string after removal
# removes ele. at 3rd index
print("The string after removal of i'th character : " + new_str)
#Output : The string after removal of i'th character : GeksForGeeks
[END] |
Ways to remove i - th character from string in python | https://www.geeksforgeeks.org/ways-to-remove-ith-character-from-string-in-python/ | # Initializing String
test_str = "GeeksForGeeks"
# Removing char at pos 3
# using join() + list comprehension
new_str = "".join([test_str[i] for i in range(len(test_str)) if i != 2])
# Printing string after removal
# removes ele. at 3rd index
print("The string after removal of i'th character : " + new_str) |
#Output : The string after removal of i'th character : GeksForGeeks | Ways to remove i - th character from string in python
# Initializing String
test_str = "GeeksForGeeks"
# Removing char at pos 3
# using join() + list comprehension
new_str = "".join([test_str[i] for i in range(len(test_str)) if i != 2])
# Printing string after removal
# removes ele. at 3rd index
print("The string after removal of i'th character : " + new_str)
#Output : The string after removal of i'th character : GeksForGeeks
[END] |
Ways to remove i - th character from string in python | https://www.geeksforgeeks.org/ways-to-remove-ith-character-from-string-in-python/ | str = "Geeks123For123Geeks"
print(str.translate({ord(i): None for i in "123"})) |
#Output : The string after removal of i'th character : GeksForGeeks | Ways to remove i - th character from string in python
str = "Geeks123For123Geeks"
print(str.translate({ord(i): None for i in "123"}))
#Output : The string after removal of i'th character : GeksForGeeks
[END] |
Ways to remove i - th character from string in python | https://www.geeksforgeeks.org/ways-to-remove-ith-character-from-string-in-python/ | def remove_ith_character(s, i):
# Base case: if index is 0, return string with first character removed
if i == 0:
return s[1:]
# Recursive case: return first character concatenated with result of calling function on string with index decremented by 1
return s[0] + remove_ith_character(s[1:], i - 1)
# Test the function
test_str = "GeeksForGeeks"
new_str = remove_ith_character(test_str, 2)
print("The string after removal of ith character:", new_str)
# This code is contributed by Edula Vinay Kumar Reddy |
#Output : The string after removal of i'th character : GeksForGeeks | Ways to remove i - th character from string in python
def remove_ith_character(s, i):
# Base case: if index is 0, return string with first character removed
if i == 0:
return s[1:]
# Recursive case: return first character concatenated with result of calling function on string with index decremented by 1
return s[0] + remove_ith_character(s[1:], i - 1)
# Test the function
test_str = "GeeksForGeeks"
new_str = remove_ith_character(test_str, 2)
print("The string after removal of ith character:", new_str)
# This code is contributed by Edula Vinay Kumar Reddy
#Output : The string after removal of i'th character : GeksForGeeks
[END] |
Ways to remove i - th character from string in python | https://www.geeksforgeeks.org/ways-to-remove-ith-character-from-string-in-python/ | def remove_char(s, i):
b = bytearray(s, "utf-8")
del b[i]
return b.decode()
# Example usage
s = "hello world"
i = 4
s = remove_char(s, i)
print(s) |
#Output : The string after removal of i'th character : GeksForGeeks | Ways to remove i - th character from string in python
def remove_char(s, i):
b = bytearray(s, "utf-8")
del b[i]
return b.decode()
# Example usage
s = "hello world"
i = 4
s = remove_char(s, i)
print(s)
#Output : The string after removal of i'th character : GeksForGeeks
[END] |
Find length of a string in python (4 ways) | https://www.geeksforgeeks.org/find-length-of-a-string-in-python-4-ways/ | # Python code to demonstrate string length
# using len
str = "geeks"
print(len(str)) | #Input : 'abc'
#Output : 3 | Find length of a string in python (4 ways)
# Python code to demonstrate string length
# using len
str = "geeks"
print(len(str))
#Input : 'abc'
#Output : 3
[END] |
Find length of a string in python (4 ways) | https://www.geeksforgeeks.org/find-length-of-a-string-in-python-4-ways/ | # Python code to demonstrate string length
# using for loop
# Returns length of string
def findLen(str):
counter = 0
for i in str:
counter += 1
return counter
str = "geeks"
print(findLen(str)) | #Input : 'abc'
#Output : 3 | Find length of a string in python (4 ways)
# Python code to demonstrate string length
# using for loop
# Returns length of string
def findLen(str):
counter = 0
for i in str:
counter += 1
return counter
str = "geeks"
print(findLen(str))
#Input : 'abc'
#Output : 3
[END] |
Find length of a string in python (4 ways) | https://www.geeksforgeeks.org/find-length-of-a-string-in-python-4-ways/ | # Python code to demonstrate string length
# using while loop.
# Returns length of string
def findLen(str):
counter = 0
while str[counter:]:
counter += 1
return counter
str = "geeks"
print(findLen(str)) | #Input : 'abc'
#Output : 3 | Find length of a string in python (4 ways)
# Python code to demonstrate string length
# using while loop.
# Returns length of string
def findLen(str):
counter = 0
while str[counter:]:
counter += 1
return counter
str = "geeks"
print(findLen(str))
#Input : 'abc'
#Output : 3
[END] |
Find length of a string in python (4 ways) | https://www.geeksforgeeks.org/find-length-of-a-string-in-python-4-ways/ | # Python code to demonstrate string length
# using join and count
# Returns length of string
def findLen(str):
if not str:
return 0
else:
some_random_str = "py"
return ((some_random_str).join(str)).count(some_random_str) + 1
str = "geeks"
print(findLen(str)) | #Input : 'abc'
#Output : 3 | Find length of a string in python (4 ways)
# Python code to demonstrate string length
# using join and count
# Returns length of string
def findLen(str):
if not str:
return 0
else:
some_random_str = "py"
return ((some_random_str).join(str)).count(some_random_str) + 1
str = "geeks"
print(findLen(str))
#Input : 'abc'
#Output : 3
[END] |
Find length of a string in python (4 ways) | https://www.geeksforgeeks.org/find-length-of-a-string-in-python-4-ways/ | # Python code to demonstrate string length
# using reduce
import functools
def findLen(string):
return functools.reduce(lambda x, y: x + 1, string, 0)
# Driver Code
string = "geeks"
print(findLen(string)) | #Input : 'abc'
#Output : 3 | Find length of a string in python (4 ways)
# Python code to demonstrate string length
# using reduce
import functools
def findLen(string):
return functools.reduce(lambda x, y: x + 1, string, 0)
# Driver Code
string = "geeks"
print(findLen(string))
#Input : 'abc'
#Output : 3
[END] |
Find length of a string in python (4 ways) | https://www.geeksforgeeks.org/find-length-of-a-string-in-python-4-ways/ | # Python code to demonstrate string length
# using sum
def findLen(string):
return sum(1 for i in string)
# Driver Code
string = "geeks"
print(findLen(string)) | #Input : 'abc'
#Output : 3 | Find length of a string in python (4 ways)
# Python code to demonstrate string length
# using sum
def findLen(string):
return sum(1 for i in string)
# Driver Code
string = "geeks"
print(findLen(string))
#Input : 'abc'
#Output : 3
[END] |
Find length of a string in python (4 ways) | https://www.geeksforgeeks.org/find-length-of-a-string-in-python-4-ways/ | # python code to find the length of
# string using enumerate function
string = "gee@1ks"
s = 0
for i, a in enumerate(string):
s += 1
print(s) | #Input : 'abc'
#Output : 3 | Find length of a string in python (4 ways)
# python code to find the length of
# string using enumerate function
string = "gee@1ks"
s = 0
for i, a in enumerate(string):
s += 1
print(s)
#Input : 'abc'
#Output : 3
[END] |
Python - Avoid Spaces in string | https://www.geeksforgeeks.org/python-avoid-spaces-in-string-length/ | # Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# Using isspace() + sum()
# initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : " + str(test_str))
# isspace() checks for space
# sum checks count
res = sum(not chr.isspace() for chr in test_str)
# printing result
print("The Characters Frequency avoiding spaces : " + str(res)) |
#Output : The original string is : geeksforgeeks 33 is best | Python - Avoid Spaces in string
# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# Using isspace() + sum()
# initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : " + str(test_str))
# isspace() checks for space
# sum checks count
res = sum(not chr.isspace() for chr in test_str)
# printing result
print("The Characters Frequency avoiding spaces : " + str(res))
#Output : The original string is : geeksforgeeks 33 is best
[END] |
Python - Avoid Spaces in string | https://www.geeksforgeeks.org/python-avoid-spaces-in-string-length/ | # Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# Using sum() + len() + map() + split()
# initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : " + str(test_str))
# len() finds individual word Frequency
# sum() extracts final Frequency
res = sum(map(len, test_str.split()))
# printing result
print("The Characters Frequency avoiding spaces : " + str(res)) |
#Output : The original string is : geeksforgeeks 33 is best | Python - Avoid Spaces in string
# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# Using sum() + len() + map() + split()
# initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : " + str(test_str))
# len() finds individual word Frequency
# sum() extracts final Frequency
res = sum(map(len, test_str.split()))
# printing result
print("The Characters Frequency avoiding spaces : " + str(res))
#Output : The original string is : geeksforgeeks 33 is best
[END] |
Python - Avoid Spaces in string | https://www.geeksforgeeks.org/python-avoid-spaces-in-string-length/ | # Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : " + str(test_str))
test_str = test_str.replace(" ", "")
res = len(test_str)
# printing result
print("The Characters Frequency avoiding spaces : " + str(res)) |
#Output : The original string is : geeksforgeeks 33 is best | Python - Avoid Spaces in string
# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : " + str(test_str))
test_str = test_str.replace(" ", "")
res = len(test_str)
# printing result
print("The Characters Frequency avoiding spaces : " + str(res))
#Output : The original string is : geeksforgeeks 33 is best
[END] |
Python - Avoid Spaces in string | https://www.geeksforgeeks.org/python-avoid-spaces-in-string-length/ | # Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : ", test_str)
# initializing count = 0
count = 0
# loop to iterate the string, character by character
for i in test_str:
if i == " ":
continue
count += 1
# printing result
print("The Characters Frequency avoiding spaces : ", count)
# This code is contributed by Pratik Gupta (guptapratik) |
#Output : The original string is : geeksforgeeks 33 is best | Python - Avoid Spaces in string
# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : ", test_str)
# initializing count = 0
count = 0
# loop to iterate the string, character by character
for i in test_str:
if i == " ":
continue
count += 1
# printing result
print("The Characters Frequency avoiding spaces : ", count)
# This code is contributed by Pratik Gupta (guptapratik)
#Output : The original string is : geeksforgeeks 33 is best
[END] |
Python - Avoid Spaces in string | https://www.geeksforgeeks.org/python-avoid-spaces-in-string-length/ | # initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : " + str(test_str))
# Using a list comprehension and the join() function
res = len("".join([char for char in test_str if char != " "]))
# printing result
print("The Characters Frequency avoiding spaces : " + str(res)) |
#Output : The original string is : geeksforgeeks 33 is best | Python - Avoid Spaces in string
# initializing string
test_str = "geeksforgeeks 33 is best"
# printing original string
print("The original string is : " + str(test_str))
# Using a list comprehension and the join() function
res = len("".join([char for char in test_str if char != " "]))
# printing result
print("The Characters Frequency avoiding spaces : " + str(res))
#Output : The original string is : geeksforgeeks 33 is best
[END] |