Description
stringlengths 9
105
| Link
stringlengths 45
135
| Code
stringlengths 10
26.8k
| Test_Case
stringlengths 9
202
| Merge
stringlengths 63
27k
|
---|---|---|---|---|
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | sentence = "hello geeks for geeks is computer science portal"
length = 4
print([word for word in sentence.split() if len(word) > length]) | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
sentence = "hello geeks for geeks is computer science portal"
length = 4
print([word for word in sentence.split() if len(word) > length])
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | let sentence = "hello geeks for geeks is computer science portal";let length = 4;let words = sentence.split(" ").filter(word => word.length > length);console.log(words);??????// This code is contributed by codebra | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
let sentence = "hello geeks for geeks is computer science portal";let length = 4;let words = sentence.split(" ").filter(word => word.length > length);console.log(words);??????// This code is contributed by codebra
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | # Python program for the above approach
# Driver Code
S = "hello geeks for geeks is computer science portal"
K = 4
s = S.split(" ")
l = list(filter(lambda x: (len(x) > K), s))
print(l) | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
# Python program for the above approach
# Driver Code
S = "hello geeks for geeks is computer science portal"
K = 4
s = S.split(" ")
l = list(filter(lambda x: (len(x) > K), s))
print(l)
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | // C++ program for the above approach#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std;??????// Function to find substring greater than Kvoid stringLengthGreaterThanK(string n, int l){????????????????????????vector<string> s;??"";??????????????????????????????// Traverse the given string n????????????????????????for (char c : n) {????????????????????????????????????????????????if (c == ' ') {?????????????????????????????????????????????????????????????????????"";????????????????????????????????????????????????????????????????????????}????????????????????????????????????????????????}????????????????????????????????????????????????else {????????????????????????????????????????????????????????????????????????word += c;????????????????????????????????????????????????}????????????????????????}????????????????????????if (word.length() > 0) {????????????????????????????????????????????????s.push_back(word);????????????????????????}??????????????????????????????// Stores the r" ";????????????????????????}}??????// Driver Codeint main()"hello geeks for geeks is computer science "??????????????????????????????"portal";????????????????????????int K = 4;????????????????????????stringLengthGreater | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
// C++ program for the above approach#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std;??????// Function to find substring greater than Kvoid stringLengthGreaterThanK(string n, int l){????????????????????????vector<string> s;??"";??????????????????????????????// Traverse the given string n????????????????????????for (char c : n) {????????????????????????????????????????????????if (c == ' ') {?????????????????????????????????????????????????????????????????????"";????????????????????????????????????????????????????????????????????????}????????????????????????????????????????????????}????????????????????????????????????????????????else {????????????????????????????????????????????????????????????????????????word += c;????????????????????????????????????????????????}????????????????????????}????????????????????????if (word.length() > 0) {????????????????????????????????????????????????s.push_back(word);????????????????????????}??????????????????????????????// Stores the r" ";????????????????????????}}??????// Driver Codeint main()"hello geeks for geeks is computer science "??????????????????????????????"portal";????????????????????????int K = 4;????????????????????????stringLengthGreater
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | // Java program for the above approach??????import java.util.*;??????public class Main {??????????????????????????????// Driver Code????????????????????????public static void main(String[]"hello geeks for geeks is computer science portal";????????????????????????????????????????????????int K = 4;?????" ");????????????????????????????????????????????????List<String> l = new ArrayList<>();??????????????????????????????????????????????????????for (String str : s) {????????????????????????????????????????????????????????????????????????if (str.length() > K) {??????????????????? | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
// Java program for the above approach??????import java.util.*;??????public class Main {??????????????????????????????// Driver Code????????????????????????public static void main(String[]"hello geeks for geeks is computer science portal";????????????????????????????????????????????????int K = 4;?????" ");????????????????????????????????????????????????List<String> l = new ArrayList<>();??????????????????????????????????????????????????????for (String str : s) {????????????????????????????????????????????????????????????????????????if (str.length() > K) {???????????????????
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | using System;using System.Linq;using System.Collections.Generic;??????public class Program{????????????????????????public static void Main()????????????????"hello geeks for geeks is computer science portal";????????????????????????????????????????????????int K = 4;????????????????????????????????????????????????string[] s = S.Split(' ');????????????????????????????????????????????????List<string> l = new List<string>();??????????????????????????????????????????????????????foreach(string word in s)????????????????????????????????????????????????{??????????????????????????????????????", ", l));?????????? | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
using System;using System.Linq;using System.Collections.Generic;??????public class Program{????????????????????????public static void Main()????????????????"hello geeks for geeks is computer science portal";????????????????????????????????????????????????int K = 4;????????????????????????????????????????????????string[] s = S.Split(' ');????????????????????????????????????????????????List<string> l = new List<string>();??????????????????????????????????????????????????????foreach(string word in s)????????????????????????????????????????????????{??????????????????????????????????????", ", l));??????????
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | // JavaScript program for the above approach??????// Driver Codelet "hello geeks for geeks is computer science portal";let K = 4;let s = S.split(" ");let l = s.filter((x) => x.length > K);??????console.log | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
// JavaScript program for the above approach??????// Driver Codelet "hello geeks for geeks is computer science portal";let K = 4;let s = S.split(" ");let l = s.filter((x) => x.length > K);??????console.log
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | sentence = "hello geeks for geeks is computer science portal"
length = 4
s = sentence.split()
print([a for i, a in enumerate(s) if len(a) > length]) | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
sentence = "hello geeks for geeks is computer science portal"
length = 4
s = sentence.split()
print([a for i, a in enumerate(s) if len(a) > length])
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | // Java program for the above approach??????import java.util.ArrayList;import java.util.List;??????public class Main {????????????????????????public static void main(String[] args)????????????????????????{?????????????????"hello geeks for geeks is computer science portal";????????????????????????????????????????????????int length = 4;????????????????????????????????????????????????// Split the sentence into words using spaces as??????????" ");??????????????????????????????????????????????????????// Find the words with length greater than the given????????????????????????????????????????????????// length.????????????????????????????????????????????????List<String> result = new ArrayList<>();????????????????????????????????????????????????for (int i = 0; i < s.length; i++) {????????????????????????????????????????????????????????????????????????if (s[i].length() > length) {???????????????????????????????????????????????????????????????" ");????????????????????????????????????????????????}??????????????? | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
// Java program for the above approach??????import java.util.ArrayList;import java.util.List;??????public class Main {????????????????????????public static void main(String[] args)????????????????????????{?????????????????"hello geeks for geeks is computer science portal";????????????????????????????????????????????????int length = 4;????????????????????????????????????????????????// Split the sentence into words using spaces as??????????" ");??????????????????????????????????????????????????????// Find the words with length greater than the given????????????????????????????????????????????????// length.????????????????????????????????????????????????List<String> result = new ArrayList<>();????????????????????????????????????????????????for (int i = 0; i < s.length; i++) {????????????????????????????????????????????????????????????????????????if (s[i].length() > length) {???????????????????????????????????????????????????????????????" ");????????????????????????????????????????????????}???????????????
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Find words which are greater than K than given length k | https://www.geeksforgeeks.org/find-words-greater-given-length-k/ | #include <iostream>#include <string>#include <vector>??????using namespace std;??????int main() {????????????????????????// Define the input sentence and minimum word length??"hello geeks for geeks is computer science portal";????????????????????????int length = 4;??????????????????????????????// Split the sentence into words and store them in a vector????????????????????????vector<string> s;????????????????????????string word;????????????????????????for (int i = 0; i < sentence.length(); i++) {??????????????????????????????"";????????????????????????????????????????????????} else {????????????????????????????????????????????????????????????????????????word += sentence[i];????????????????????????????????????????????????}????????????????????????}????????????????????????s.push_back(word);??????????????????????????????// Filter out words shorter than the minimum length and store them in a new vector????????????????????????vector<string> l;????????????????????????for (int i = 0; i < s.size(); i++) {??????????????????????????????" ";????????????????????????}????????????????????????c | #Input : str = "hello geeks for geeks
is computer science portal" | Find words which are greater than K than given length k
#include <iostream>#include <string>#include <vector>??????using namespace std;??????int main() {????????????????????????// Define the input sentence and minimum word length??"hello geeks for geeks is computer science portal";????????????????????????int length = 4;??????????????????????????????// Split the sentence into words and store them in a vector????????????????????????vector<string> s;????????????????????????string word;????????????????????????for (int i = 0; i < sentence.length(); i++) {??????????????????????????????"";????????????????????????????????????????????????} else {????????????????????????????????????????????????????????????????????????word += sentence[i];????????????????????????????????????????????????}????????????????????????}????????????????????????s.push_back(word);??????????????????????????????// Filter out words shorter than the minimum length and store them in a new vector????????????????????????vector<string> l;????????????????????????for (int i = 0; i < s.size(); i++) {??????????????????????????????" ";????????????????????????}????????????????????????c
#Input : str = "hello geeks for geeks
is computer science portal"
[END] |
Python program for removing i-th character from a string | https://www.geeksforgeeks.org/python-program-for-removing-i-th-character-from-a-string/ | # Python3 program for removing i-th
# indexed character from a string
# Removes character at index i
def remove(string, i):
# Characters before the i-th indexed
# is stored in a variable a
a = string[:i]
# Characters after the nth indexed
# is stored in a variable b
b = string[i + 1 :]
# Returning string after removing
# nth indexed character.
return a + b
# Driver Code
if __name__ == "__main__":
string = "geeksFORgeeks"
# Remove nth index element
i = 5
# Print the new string
print(remove(string, i)) |
#Output : g e e k s
| Python program for removing i-th character from a string
# Python3 program for removing i-th
# indexed character from a string
# Removes character at index i
def remove(string, i):
# Characters before the i-th indexed
# is stored in a variable a
a = string[:i]
# Characters after the nth indexed
# is stored in a variable b
b = string[i + 1 :]
# Returning string after removing
# nth indexed character.
return a + b
# Driver Code
if __name__ == "__main__":
string = "geeksFORgeeks"
# Remove nth index element
i = 5
# Print the new string
print(remove(string, i))
#Output : g e e k s
[END] |
Python program for removing i-th character from a string | https://www.geeksforgeeks.org/python-program-for-removing-i-th-character-from-a-string/ | # Python3 program for removing i-th
# indexed character from a string
# Removes character at index i
def remove(string, i):
for j in range(len(string)):
if j == i:
string = string.replace(string[i], "", 1)
return string
# Driver Code
if __name__ == "__main__":
string = "geeksFORgeeks"
# Remove nth index element
i = 5
# Print the new string
print(remove(string, i)) |
#Output : g e e k s
| Python program for removing i-th character from a string
# Python3 program for removing i-th
# indexed character from a string
# Removes character at index i
def remove(string, i):
for j in range(len(string)):
if j == i:
string = string.replace(string[i], "", 1)
return string
# Driver Code
if __name__ == "__main__":
string = "geeksFORgeeks"
# Remove nth index element
i = 5
# Print the new string
print(remove(string, i))
#Output : g e e k s
[END] |
Python program for removing i-th character from a string | https://www.geeksforgeeks.org/python-program-for-removing-i-th-character-from-a-string/ | # Python3 program for removing i-th
# indexed character from a string
# Removes character at index i
def remove(string, i):
if i > len(string):
return string
a = list(string)
a.pop(i)
return "".join(a)
# Driver Code
if __name__ == "__main__":
string = "geeksFORgeeks"
# Remove nth index element
i = 2
# Print the new string
print(remove(string, i)) |
#Output : g e e k s
| Python program for removing i-th character from a string
# Python3 program for removing i-th
# indexed character from a string
# Removes character at index i
def remove(string, i):
if i > len(string):
return string
a = list(string)
a.pop(i)
return "".join(a)
# Driver Code
if __name__ == "__main__":
string = "geeksFORgeeks"
# Remove nth index element
i = 2
# Print the new string
print(remove(string, i))
#Output : g e e k s
[END] |
Python program for removing i-th character from a string | https://www.geeksforgeeks.org/python-program-for-removing-i-th-character-from-a-string/ | def remove(string, i):
return "".join()
print(remove("geeksforgeeks", 2)) |
#Output : g e e k s
| Python program for removing i-th character from a string
def remove(string, i):
return "".join()
print(remove("geeksforgeeks", 2))
#Output : g e e k s
[END] |
Python program for removing i-th character from a string | https://www.geeksforgeeks.org/python-program-for-removing-i-th-character-from-a-string/ | # Python3 program for removing i-th
# indexed character from a string
# Removes character at index i
import re
def remove(string, i):
pattern = f"(^.{{{i}}})(.)"
return re.sub(pattern, r"\1", string)
# Driver Code
if __name__ == "__main__":
string = "geeksFORgeeks"
# i-th index to be removed
i = 5
# string after removal of i-th index
print(remove(string, i)) |
#Output : g e e k s
| Python program for removing i-th character from a string
# Python3 program for removing i-th
# indexed character from a string
# Removes character at index i
import re
def remove(string, i):
pattern = f"(^.{{{i}}})(.)"
return re.sub(pattern, r"\1", string)
# Driver Code
if __name__ == "__main__":
string = "geeksFORgeeks"
# i-th index to be removed
i = 5
# string after removal of i-th index
print(remove(string, i))
#Output : g e e k s
[END] |
Python program to split and join a string | https://www.geeksforgeeks.org/python-program-split-join-string/ | # Python program to split a string and
# join it using different delimiter
def split_string(string):
# Split the string based on space delimiter
list_string = string.split(" ")
return list_string
def join_string(list_string):
# Join the string based on '-' delimiter
string = "-".join(list_string)
return string
# Driver Function
if __name__ == "__main__":
string = "Geeks for Geeks"
# Splitting a string
list_string = split_string(string)
print(list_string)
# Join list of strings into one
new_string = join_string(list_string)
print(new_string) | #Input : Geeks for Geeks
Split the string into list of strings | Python program to split and join a string
# Python program to split a string and
# join it using different delimiter
def split_string(string):
# Split the string based on space delimiter
list_string = string.split(" ")
return list_string
def join_string(list_string):
# Join the string based on '-' delimiter
string = "-".join(list_string)
return string
# Driver Function
if __name__ == "__main__":
string = "Geeks for Geeks"
# Splitting a string
list_string = split_string(string)
print(list_string)
# Join list of strings into one
new_string = join_string(list_string)
print(new_string)
#Input : Geeks for Geeks
Split the string into list of strings
[END] |
Python program to split and join a string | https://www.geeksforgeeks.org/python-program-split-join-string/ | # Python code
# to split and join given string
# input string
s = "Geeks for Geeks"
# print the string after split method
print(s.split(" "))
# print the string after join method
print("-".join(s.split()))
# this code is contributed by gangarajula laxmi | #Input : Geeks for Geeks
Split the string into list of strings | Python program to split and join a string
# Python code
# to split and join given string
# input string
s = "Geeks for Geeks"
# print the string after split method
print(s.split(" "))
# print the string after join method
print("-".join(s.split()))
# this code is contributed by gangarajula laxmi
#Input : Geeks for Geeks
Split the string into list of strings
[END] |
Python program to split and join a string | https://www.geeksforgeeks.org/python-program-split-join-string/ | import re
def split_and_join(string):
# Split the string using a regular expression to match any sequence of non-alphabetic characters as the delimiter
split_string = re.split(r"[^a-zA-Z]", string)
# Join the list of strings with a '-' character between them
joined_string = ""
for i, s in enumerate(split_string):
if i > 0:
joined_string += "-"
joined_string += s
return split_string, joined_string
# Test the function
string = "Geeks for Geeks"
split_string, joined_string = split_and_join(string)
print(split_string)
print(joined_string) | #Input : Geeks for Geeks
Split the string into list of strings | Python program to split and join a string
import re
def split_and_join(string):
# Split the string using a regular expression to match any sequence of non-alphabetic characters as the delimiter
split_string = re.split(r"[^a-zA-Z]", string)
# Join the list of strings with a '-' character between them
joined_string = ""
for i, s in enumerate(split_string):
if i > 0:
joined_string += "-"
joined_string += s
return split_string, joined_string
# Test the function
string = "Geeks for Geeks"
split_string, joined_string = split_and_join(string)
print(split_string)
print(joined_string)
#Input : Geeks for Geeks
Split the string into list of strings
[END] |
Python program to split and join a string | https://www.geeksforgeeks.org/python-program-split-join-string/ | # Python code
# to split and join given string
import re
# input string
s = "Geeks for Geeks"
# print the string after split method
print(re.findall(r"[a-zA-Z]+", s))
# print the string after join method
print("-".join(re.findall(r"[a-zA-Z]+", s))) | #Input : Geeks for Geeks
Split the string into list of strings | Python program to split and join a string
# Python code
# to split and join given string
import re
# input string
s = "Geeks for Geeks"
# print the string after split method
print(re.findall(r"[a-zA-Z]+", s))
# print the string after join method
print("-".join(re.findall(r"[a-zA-Z]+", s)))
#Input : Geeks for Geeks
Split the string into list of strings
[END] |
Python program to split and join a string | https://www.geeksforgeeks.org/python-program-split-join-string/ | import re
def split_string(string):
list_string = re.split("\s+", string)
return list_string
def join_string(list_string):
new_string = "-".join(list_string)
return new_string
if __name__ == "__main__":
string = "Geeks for Geeks"
# Splitting a string
list_string = split_string(string)
print(list_string)
# Join list of strings into one
new_string = join_string(list_string)
print(new_string)
# This code is contributed by Vinay Pinjala. | #Input : Geeks for Geeks
Split the string into list of strings | Python program to split and join a string
import re
def split_string(string):
list_string = re.split("\s+", string)
return list_string
def join_string(list_string):
new_string = "-".join(list_string)
return new_string
if __name__ == "__main__":
string = "Geeks for Geeks"
# Splitting a string
list_string = split_string(string)
print(list_string)
# Join list of strings into one
new_string = join_string(list_string)
print(new_string)
# This code is contributed by Vinay Pinjala.
#Input : Geeks for Geeks
Split the string into list of strings
[END] |
Python | Check if a given string is binary string or notor not | https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/ | # Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
# set function convert string
# into set of characters .
p = set(string)
# declare set of '0', '1' .
s = {"0", "1"}
# check set p is same as set s
# or set p contains only '0'
# or set p contains only '1'
# or not, if any one condition
# is true then string is accepted
# otherwise not .
if s == p or p == {"0"} or p == {"1"}:
print("Yes")
else:
print("No")
# driver code
if __name__ == "__main__":
string = "101010000111"
# function calling
check(string) | Input: str = "01010101010"
Output: Yes | Python | Check if a given string is binary string or notor not
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
# set function convert string
# into set of characters .
p = set(string)
# declare set of '0', '1' .
s = {"0", "1"}
# check set p is same as set s
# or set p contains only '0'
# or set p contains only '1'
# or not, if any one condition
# is true then string is accepted
# otherwise not .
if s == p or p == {"0"} or p == {"1"}:
print("Yes")
else:
print("No")
# driver code
if __name__ == "__main__":
string = "101010000111"
# function calling
check(string)
Input: str = "01010101010"
Output: Yes
[END] |
Python | Check if a given string is binary string or notor not | https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/ | # Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check2(string):
# initialize the variable t
# with '01' string
t = "01"
# initialize the variable count
# with 0 value
count = 0
# looping through each character
# of the string .
for char in string:
# check the character is present in
# string t or not.
# if this condition is true
# assign 1 to the count variable
# and break out of the for loop
# otherwise pass
if char not in t:
count = 1
break
else:
pass
# after coming out of the loop
# check value of count is non-zero or not
# if the value is non-zero the en condition is true
# and string is not accepted
# otherwise string is accepted
if count:
print("No")
else:
print("Yes")
# driver code
if __name__ == "__main__":
string = "001021010001010"
# function calling
check2(string) | Input: str = "01010101010"
Output: Yes | Python | Check if a given string is binary string or notor not
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check2(string):
# initialize the variable t
# with '01' string
t = "01"
# initialize the variable count
# with 0 value
count = 0
# looping through each character
# of the string .
for char in string:
# check the character is present in
# string t or not.
# if this condition is true
# assign 1 to the count variable
# and break out of the for loop
# otherwise pass
if char not in t:
count = 1
break
else:
pass
# after coming out of the loop
# check value of count is non-zero or not
# if the value is non-zero the en condition is true
# and string is not accepted
# otherwise string is accepted
if count:
print("No")
else:
print("Yes")
# driver code
if __name__ == "__main__":
string = "001021010001010"
# function calling
check2(string)
Input: str = "01010101010"
Output: Yes
[END] |
Python | Check if a given string is binary string or notor not | https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/ | # import library
import re
sampleInput = "1001010"
# regular expression to find the strings
# which have characters other than 0 and 1
c = re.compile("[^01]")
# use findall() to get the list of strings
# that have characters other than 0 and 1.
if len(c.findall(sampleInput)):
print("No") # if length of list > 0 then it is not binary
else:
print("Yes") # if length of list = 0 then it is binary | Input: str = "01010101010"
Output: Yes | Python | Check if a given string is binary string or notor not
# import library
import re
sampleInput = "1001010"
# regular expression to find the strings
# which have characters other than 0 and 1
c = re.compile("[^01]")
# use findall() to get the list of strings
# that have characters other than 0 and 1.
if len(c.findall(sampleInput)):
print("No") # if length of list > 0 then it is not binary
else:
print("Yes") # if length of list = 0 then it is binary
Input: str = "01010101010"
Output: Yes
[END] |
Python | Check if a given string is binary string or notor not | https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/ | # Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
try:
# this will raise value error if
# string is not of base 2
int(string, 2)
except ValueError:
return "No"
return "Yes"
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(check(string1))
print(check(string2))
# this code is contributed by phasing17 | Input: str = "01010101010"
Output: Yes | Python | Check if a given string is binary string or notor not
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
try:
# this will raise value error if
# string is not of base 2
int(string, 2)
except ValueError:
return "No"
return "Yes"
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(check(string1))
print(check(string2))
# this code is contributed by phasing17
Input: str = "01010101010"
Output: Yes
[END] |
Python | Check if a given string is binary string or notor not | https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/ | string = "01010101010"
if string.count("0") + string.count("1") == len(string):
print("Yes")
else:
print("No") | Input: str = "01010101010"
Output: Yes | Python | Check if a given string is binary string or notor not
string = "01010101010"
if string.count("0") + string.count("1") == len(string):
print("Yes")
else:
print("No")
Input: str = "01010101010"
Output: Yes
[END] |
Python | Check if a given string is binary string or notor not | https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/ | # Python program to check string is binary or not
string = "01010121010"
binary = "01"
for i in binary:
string = string.replace(i, "")
if len(string) == 0:
print("Yes")
else:
print("No") | Input: str = "01010101010"
Output: Yes | Python | Check if a given string is binary string or notor not
# Python program to check string is binary or not
string = "01010121010"
binary = "01"
for i in binary:
string = string.replace(i, "")
if len(string) == 0:
print("Yes")
else:
print("No")
Input: str = "01010101010"
Output: Yes
[END] |
Python | Check if a given string is binary string or notor not | https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/ | # Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
if all((letter in "01") for letter in string):
return "Yes"
return "No"
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(check(string1))
print(check(string2))
# this code is contributed by phasing17 | Input: str = "01010101010"
Output: Yes | Python | Check if a given string is binary string or notor not
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
if all((letter in "01") for letter in string):
return "Yes"
return "No"
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(check(string1))
print(check(string2))
# this code is contributed by phasing17
Input: str = "01010101010"
Output: Yes
[END] |
Python | Check if a given string is binary string or notor not | https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/ | def is_binary_string(s):
# use set comprehension to extract all unique characters from the string
unique_chars = {c for c in s}
# check if the unique characters are only 0 and 1
return unique_chars.issubset({"0", "1"})
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(is_binary_string(string1))
print(is_binary_string(string2)) | Input: str = "01010101010"
Output: Yes | Python | Check if a given string is binary string or notor not
def is_binary_string(s):
# use set comprehension to extract all unique characters from the string
unique_chars = {c for c in s}
# check if the unique characters are only 0 and 1
return unique_chars.issubset({"0", "1"})
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(is_binary_string(string1))
print(is_binary_string(string2))
Input: str = "01010101010"
Output: Yes
[END] |
Python | Check if a given string is binary string or notor not | https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/ | import re
def is_binary_string(str):
# Define regular expression
regex = r"[^01]"
# Search for regular expression in string
if re.search(regex, str):
return False
else:
return True
# Examples
print(is_binary_string("01010101010")) # Output: Yes
print(is_binary_string("geeks101")) # Output: No | Input: str = "01010101010"
Output: Yes | Python | Check if a given string is binary string or notor not
import re
def is_binary_string(str):
# Define regular expression
regex = r"[^01]"
# Search for regular expression in string
if re.search(regex, str):
return False
else:
return True
# Examples
print(is_binary_string("01010101010")) # Output: Yes
print(is_binary_string("geeks101")) # Output: No
Input: str = "01010101010"
Output: Yes
[END] |
Python | Find all close matches of input string from a list | https://www.geeksforgeeks.org/python-find-close-matches-input-string-list/ | # Function to find all close matches of
# input string in given list of possible strings
from difflib import get_close_matches
def closeMatches(patterns, word):
print(get_close_matches(word, patterns))
# Driver program
if __name__ == "__main__":
word = "appel"
patterns = ["ape", "apple", "peach", "puppy"]
closeMatches(patterns, word) | #Input : patterns = ['ape', 'apple',
'peach', 'puppy'], | Python | Find all close matches of input string from a list
# Function to find all close matches of
# input string in given list of possible strings
from difflib import get_close_matches
def closeMatches(patterns, word):
print(get_close_matches(word, patterns))
# Driver program
if __name__ == "__main__":
word = "appel"
patterns = ["ape", "apple", "peach", "puppy"]
closeMatches(patterns, word)
#Input : patterns = ['ape', 'apple',
'peach', 'puppy'],
[END] |
Python program to find uncommon words from two Strings | https://www.geeksforgeeks.org/python-program-to-find-uncommon-words-from-two-strings/ | # Python3 program to find a list of uncommon words
# Function to return all uncommon words
def UncommonWords(A, B):
# count will contain all the word counts
count = {}
# insert words of string A to hash
for word in A.split():
count[word] = count.get(word, 0) + 1
# insert words of string B to hash
for word in B.split():
count[word] = count.get(word, 0) + 1
# return required list of words
return [word for word in count if count[word] == 1]
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B)) |
#Output : ['Learning', 'from'] | Python program to find uncommon words from two Strings
# Python3 program to find a list of uncommon words
# Function to return all uncommon words
def UncommonWords(A, B):
# count will contain all the word counts
count = {}
# insert words of string A to hash
for word in A.split():
count[word] = count.get(word, 0) + 1
# insert words of string B to hash
for word in B.split():
count[word] = count.get(word, 0) + 1
# return required list of words
return [word for word in count if count[word] == 1]
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B))
#Output : ['Learning', 'from']
[END] |
Python program to find uncommon words from two Strings | https://www.geeksforgeeks.org/python-program-to-find-uncommon-words-from-two-strings/ | # Python3 program to find a list of uncommon words
# Function to return all uncommon words
def UncommonWords(A, B):
A = A.split()
B = B.split()
x = []
for i in A:
if i not in B:
x.append(i)
for i in B:
if i not in A:
x.append(i)
x = list(set(x))
return x
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B)) |
#Output : ['Learning', 'from'] | Python program to find uncommon words from two Strings
# Python3 program to find a list of uncommon words
# Function to return all uncommon words
def UncommonWords(A, B):
A = A.split()
B = B.split()
x = []
for i in A:
if i not in B:
x.append(i)
for i in B:
if i not in A:
x.append(i)
x = list(set(x))
return x
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B))
#Output : ['Learning', 'from']
[END] |
Python program to find uncommon words from two Strings | https://www.geeksforgeeks.org/python-program-to-find-uncommon-words-from-two-strings/ | # Python3 program to find a list of uncommon words
# Function to return all uncommon words
from collections import Counter
def UncommonWords(A, B):
A = A.split()
B = B.split()
frequency_arr1 = Counter(A)
frequency_arr2 = Counter(B)
result = []
for key in frequency_arr1:
if key not in frequency_arr2:
result.append(key)
for key in frequency_arr2:
if key not in frequency_arr1:
result.append(key)
return result
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B)) |
#Output : ['Learning', 'from'] | Python program to find uncommon words from two Strings
# Python3 program to find a list of uncommon words
# Function to return all uncommon words
from collections import Counter
def UncommonWords(A, B):
A = A.split()
B = B.split()
frequency_arr1 = Counter(A)
frequency_arr2 = Counter(B)
result = []
for key in frequency_arr1:
if key not in frequency_arr2:
result.append(key)
for key in frequency_arr2:
if key not in frequency_arr1:
result.append(key)
return result
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B))
#Output : ['Learning', 'from']
[END] |
Python program to find uncommon words from two Strings | https://www.geeksforgeeks.org/python-program-to-find-uncommon-words-from-two-strings/ | # Python3 program to find a list of uncommon words
import operator as op
# Function to return all uncommon words
def UncommonWords(A, B):
A = A.split()
B = B.split()
x = []
for i in A:
if op.countOf(B, i) == 0:
x.append(i)
for i in B:
if op.countOf(A, i) == 0:
x.append(i)
x = list(set(x))
return x
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B)) |
#Output : ['Learning', 'from'] | Python program to find uncommon words from two Strings
# Python3 program to find a list of uncommon words
import operator as op
# Function to return all uncommon words
def UncommonWords(A, B):
A = A.split()
B = B.split()
x = []
for i in A:
if op.countOf(B, i) == 0:
x.append(i)
for i in B:
if op.countOf(A, i) == 0:
x.append(i)
x = list(set(x))
return x
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B))
#Output : ['Learning', 'from']
[END] |
Python program to find uncommon words from two Strings | https://www.geeksforgeeks.org/python-program-to-find-uncommon-words-from-two-strings/ | # Python3 program to find a list of uncommon words
# Function to return all uncommon words
def UncommonWords(A, B):
# split the strings A and B into words and create sets
setA = set(A.split())
setB = set(B.split())
# find the uncommon words in setA and setB and combine them
uncommonWords = setA.difference(setB).union(setB.difference(setA))
# convert the set to a list and return
return list(uncommonWords)
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B)) |
#Output : ['Learning', 'from'] | Python program to find uncommon words from two Strings
# Python3 program to find a list of uncommon words
# Function to return all uncommon words
def UncommonWords(A, B):
# split the strings A and B into words and create sets
setA = set(A.split())
setB = set(B.split())
# find the uncommon words in setA and setB and combine them
uncommonWords = setA.difference(setB).union(setB.difference(setA))
# convert the set to a list and return
return list(uncommonWords)
# Driver Code
A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
# Print required answer
print(UncommonWords(A, B))
#Output : ['Learning', 'from']
[END] |
Python | Swap commas and dots in a String | https://www.geeksforgeeks.org/python-swap-commas-dots-string/ | # Python code to replace, with . and vice-versa
def Replace(str1):
maketrans = str1.maketrans
final = str1.translate(maketrans(",.", ".,", " "))
return final.replace(",", ", ")
# Driving Code
string = "14, 625, 498.002"
print(Replace(string)) |
#Output : 14.625.498, 002 | Python | Swap commas and dots in a String
# Python code to replace, with . and vice-versa
def Replace(str1):
maketrans = str1.maketrans
final = str1.translate(maketrans(",.", ".,", " "))
return final.replace(",", ", ")
# Driving Code
string = "14, 625, 498.002"
print(Replace(string))
#Output : 14.625.498, 002
[END] |
Python | Swap commas and dots in a String | https://www.geeksforgeeks.org/python-swap-commas-dots-string/ | def Replace(str1):
str1 = str1.replace(", ", "third")
str1 = str1.replace(".", ", ")
str1 = str1.replace("third", ".")
return str1
string = "14, 625, 498.002"
print(Replace(string)) |
#Output : 14.625.498, 002 | Python | Swap commas and dots in a String
def Replace(str1):
str1 = str1.replace(", ", "third")
str1 = str1.replace(".", ", ")
str1 = str1.replace("third", ".")
return str1
string = "14, 625, 498.002"
print(Replace(string))
#Output : 14.625.498, 002
[END] |
Python | Swap commas and dots in a String | https://www.geeksforgeeks.org/python-swap-commas-dots-string/ | import re
txt = "14, 625, 498.002"
x = re.sub(", ", "sub", txt)
x = re.sub("\.", ", ", x)
x = re.sub("sub", ".", x)
print(x)
# contributed by prachijpatel1 |
#Output : 14.625.498, 002 | Python | Swap commas and dots in a String
import re
txt = "14, 625, 498.002"
x = re.sub(", ", "sub", txt)
x = re.sub("\.", ", ", x)
x = re.sub("sub", ".", x)
print(x)
# contributed by prachijpatel1
#Output : 14.625.498, 002
[END] |
Python | Swap commas and dots in a String | https://www.geeksforgeeks.org/python-swap-commas-dots-string/ | # Approach 4: Using split and join
def Replace(str1):
str1 = "$".join(str1.split(", "))
str1 = ", ".join(str1.split("."))
str1 = ".".join(str1.split("$"))
return str1
string = "14, 625, 498.002"
print(Replace(string))
# This code is contributed by Edula Vinay Kumar Reddy |
#Output : 14.625.498, 002 | Python | Swap commas and dots in a String
# Approach 4: Using split and join
def Replace(str1):
str1 = "$".join(str1.split(", "))
str1 = ", ".join(str1.split("."))
str1 = ".".join(str1.split("$"))
return str1
string = "14, 625, 498.002"
print(Replace(string))
# This code is contributed by Edula Vinay Kumar Reddy
#Output : 14.625.498, 002
[END] |
Python | Swap commas and dots in a String | https://www.geeksforgeeks.org/python-swap-commas-dots-string/ | # Python code to replace, with . and vice-versa
def Replace(str1):
arr = []
for i in str1:
if i == ".":
arr.append(", ")
elif i == ",":
arr.append(".")
continue
elif i == " ":
continue
else:
arr.append(i)
str2 = "".join(arr)
return str2
# Driving Code
string = "14, 625, 498.002"
print(Replace(string))
# This code is contributed by Pratik Gupta |
#Output : 14.625.498, 002 | Python | Swap commas and dots in a String
# Python code to replace, with . and vice-versa
def Replace(str1):
arr = []
for i in str1:
if i == ".":
arr.append(", ")
elif i == ",":
arr.append(".")
continue
elif i == " ":
continue
else:
arr.append(i)
str2 = "".join(arr)
return str2
# Driving Code
string = "14, 625, 498.002"
print(Replace(string))
# This code is contributed by Pratik Gupta
#Output : 14.625.498, 002
[END] |
Python | Swap commas and dots in a String | https://www.geeksforgeeks.org/python-swap-commas-dots-string/ | from functools import reduce
string = "14, 625, 498.002"
result = reduce(
lambda acc, char: acc.replace(char[0], char[1]),
[(".", ", "), (", ", "."), (" ", "")],
string,
)
print(result)
# This code is contributed by Rayudu. |
#Output : 14.625.498, 002 | Python | Swap commas and dots in a String
from functools import reduce
string = "14, 625, 498.002"
result = reduce(
lambda acc, char: acc.replace(char[0], char[1]),
[(".", ", "), (", ", "."), (" ", "")],
string,
)
print(result)
# This code is contributed by Rayudu.
#Output : 14.625.498, 002
[END] |
Python | Permutation of a given string using inbuilt function | https://www.geeksforgeeks.org/python-permutation-given-string-using-inbuilt-function/ | # Function to find permutations of a given string
from itertools import permutations
def allPermutations(str):
# Get all permutations of string 'ABC'
permList = permutations(str)
# print all permutations
for perm in list(permList):
print("".join(perm))
# Driver program
if __name__ == "__main__":
str = "ABC"
allPermutations(str) | #Input : str = 'ABC'
#Output : ABC | Python | Permutation of a given string using inbuilt function
# Function to find permutations of a given string
from itertools import permutations
def allPermutations(str):
# Get all permutations of string 'ABC'
permList = permutations(str)
# print all permutations
for perm in list(permList):
print("".join(perm))
# Driver program
if __name__ == "__main__":
str = "ABC"
allPermutations(str)
#Input : str = 'ABC'
#Output : ABC
[END] |
Python | Permutation of a given string using inbuilt function | https://www.geeksforgeeks.org/python-permutation-given-string-using-inbuilt-function/ | from itertools import permutations
import string
s = "GEEK"
a = string.ascii_letters
p = permutations(s)
# Create a dictionary
d = []
for i in list(p):
# Print only if not in dictionary
if i not in d:
d.append(i)
print("".join(i)) | #Input : str = 'ABC'
#Output : ABC | Python | Permutation of a given string using inbuilt function
from itertools import permutations
import string
s = "GEEK"
a = string.ascii_letters
p = permutations(s)
# Create a dictionary
d = []
for i in list(p):
# Print only if not in dictionary
if i not in d:
d.append(i)
print("".join(i))
#Input : str = 'ABC'
#Output : ABC
[END] |
Python | Permutation of a given string using inbuilt function | https://www.geeksforgeeks.org/python-permutation-given-string-using-inbuilt-function/ | def generate_permutations(string):
if len(string) == 1:
return [string]
permutations = []
for i in range(len(string)):
fixed_char = string[i]
remaining_chars = string[:i] + string[i + 1 :]
for perm in generate_permutations(remaining_chars):
permutations.append(fixed_char + perm)
return permutations
string = "GEEK"
permutations_list = generate_permutations(string)
z = set(permutations_list)
for perm in z:
print(perm) | #Input : str = 'ABC'
#Output : ABC | Python | Permutation of a given string using inbuilt function
def generate_permutations(string):
if len(string) == 1:
return [string]
permutations = []
for i in range(len(string)):
fixed_char = string[i]
remaining_chars = string[:i] + string[i + 1 :]
for perm in generate_permutations(remaining_chars):
permutations.append(fixed_char + perm)
return permutations
string = "GEEK"
permutations_list = generate_permutations(string)
z = set(permutations_list)
for perm in z:
print(perm)
#Input : str = 'ABC'
#Output : ABC
[END] |
Python | Check for URL in a String | https://www.geeksforgeeks.org/python-check-url-string/ | # Python code to find the URL from an input string
# Using the regular expression
import re
def Find(string):
# findall() has been used
# with valid conditions for urls in string
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>????????????????????"
url = re.findall(regex, string)
return [x[0] for x in url]
# Driver Code
string = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
print("Urls: ", Find(string)) | #Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles | Python | Check for URL in a String
# Python code to find the URL from an input string
# Using the regular expression
import re
def Find(string):
# findall() has been used
# with valid conditions for urls in string
regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>????????????????????"
url = re.findall(regex, string)
return [x[0] for x in url]
# Driver Code
string = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
print("Urls: ", Find(string))
#Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles
[END] |
Python | Check for URL in a String | https://www.geeksforgeeks.org/python-check-url-string/ | # Python code to find the URL from an input string
def Find(string):
x = string.split()
res = []
for i in x:
if i.startswith("https:") or i.startswith("http:"):
res.append(i)
return res
# Driver Code
string = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
print("Urls: ", Find(string)) | #Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles | Python | Check for URL in a String
# Python code to find the URL from an input string
def Find(string):
x = string.split()
res = []
for i in x:
if i.startswith("https:") or i.startswith("http:"):
res.append(i)
return res
# Driver Code
string = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
print("Urls: ", Find(string))
#Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles
[END] |
Python | Check for URL in a String | https://www.geeksforgeeks.org/python-check-url-string/ | # Python code to find the URL from an input string
def Find(string):
x = string.split()
res = []
for i in x:
if i.find("https:") == 0 or i.find("http:") == 0:
res.append(i)
return res
# Driver Code
string = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
print("Urls: ", Find(string)) | #Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles | Python | Check for URL in a String
# Python code to find the URL from an input string
def Find(string):
x = string.split()
res = []
for i in x:
if i.find("https:") == 0 or i.find("http:") == 0:
res.append(i)
return res
# Driver Code
string = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
print("Urls: ", Find(string))
#Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles
[END] |
Python | Check for URL in a String | https://www.geeksforgeeks.org/python-check-url-string/ | from urllib.parse import urlparse
string = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
# Split the string into words
words = string.split()
# Extract URLs from the words using urlparse()
urls = []
for word in words:
parsed = urlparse(word)
if parsed.scheme and parsed.netloc:
urls.append(word)
# Print the extracted URLs
print("URLs:", urls) | #Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles | Python | Check for URL in a String
from urllib.parse import urlparse
string = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
# Split the string into words
words = string.split()
# Extract URLs from the words using urlparse()
urls = []
for word in words:
parsed = urlparse(word)
if parsed.scheme and parsed.netloc:
urls.append(word)
# Print the extracted URLs
print("URLs:", urls)
#Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles
[END] |
Python | Check for URL in a String | https://www.geeksforgeeks.org/python-check-url-string/ | from functools import reduce
def merge_url_lists(url_list1, url_list2):
return url_list1 + url_list2
def find_urls_in_string(string):
x = string.split()
return [i for i in x if i.find("https:") == 0 or i.find("http:") == 0]
string1 = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
string2 = "Some more text without URLs"
string_list = [string1, string2]
url_list = reduce(merge_url_lists, map(find_urls_in_string, string_list))
print("Urls:", url_list)
# This code is contributed by Rayudu. | #Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles | Python | Check for URL in a String
from functools import reduce
def merge_url_lists(url_list1, url_list2):
return url_list1 + url_list2
def find_urls_in_string(string):
x = string.split()
return [i for i in x if i.find("https:") == 0 or i.find("http:") == 0]
string1 = "My Profile: https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles in the portal of https://www.geeksforgeeks.org/"
string2 = "Some more text without URLs"
string_list = [string1, string2]
url_list = reduce(merge_url_lists, map(find_urls_in_string, string_list))
print("Urls:", url_list)
# This code is contributed by Rayudu.
#Input : string = 'My Profile:
https://auth.geeksforgeeks.org/user/Chinmoy%20Lenka/articles
[END] |
Execute a String of Code in Python | https://www.geeksforgeeks.org/execute-string-code-python/ | # Python program to illustrate use of exec to
# execute a given code as string.
# function illustrating how exec() functions.
def exec_code():
LOC = """
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
"""
exec(LOC)
# Driver Code
exec_code() | Input:
code = """ a = 6+5 | Execute a String of Code in Python
# Python program to illustrate use of exec to
# execute a given code as string.
# function illustrating how exec() functions.
def exec_code():
LOC = """
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
"""
exec(LOC)
# Driver Code
exec_code()
Input:
code = """ a = 6+5
[END] |
Execute a String of Code in Python | https://www.geeksforgeeks.org/execute-string-code-python/ | code = "6+5"
result = eval(code)
print(result) # Output: 11 | Input:
code = """ a = 6+5 | Execute a String of Code in Python
code = "6+5"
result = eval(code)
print(result) # Output: 11
Input:
code = """ a = 6+5
[END] |
Execute a String of Code in Python | https://www.geeksforgeeks.org/execute-string-code-python/ | code = '"hello" + "world"'
result = eval(code)
print(result) # Output: "hello world"
code = '["a", "b", "c"][1]'
result = eval(code)
print(result) # Output: "b" | Input:
code = """ a = 6+5 | Execute a String of Code in Python
code = '"hello" + "world"'
result = eval(code)
print(result) # Output: "hello world"
code = '["a", "b", "c"][1]'
result = eval(code)
print(result) # Output: "b"
Input:
code = """ a = 6+5
[END] |
Execute a String of Code in Python | https://www.geeksforgeeks.org/execute-string-code-python/ | import types
code_string = "a = 6+5"
my_namespace = types.SimpleNamespace()
exec(code_string, my_namespace.__dict__)
print(my_namespace.a) # 11 | Input:
code = """ a = 6+5 | Execute a String of Code in Python
import types
code_string = "a = 6+5"
my_namespace = types.SimpleNamespace()
exec(code_string, my_namespace.__dict__)
print(my_namespace.a) # 11
Input:
code = """ a = 6+5
[END] |
Python | Convert numeric words to numbers | https://www.geeksforgeeks.org/python-convert-numeric-words-to-numbers/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Convert numeric words to numbers
# Using join() + split()
help_dict = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"zero": "0",
}
# initializing string
test_str = "zero four zero one"
# printing original string
print("The original string is : " + test_str)
# Convert numeric words to numbers
# Using join() + split()
res = "".join(help_dict[ele] for ele in test_str.split())
# printing result
print("The string after performing replace : " + res) |
#Output : The original string is : zero four zero one | Python | Convert numeric words to numbers
# Python3 code to demonstrate working of
# Convert numeric words to numbers
# Using join() + split()
help_dict = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"zero": "0",
}
# initializing string
test_str = "zero four zero one"
# printing original string
print("The original string is : " + test_str)
# Convert numeric words to numbers
# Using join() + split()
res = "".join(help_dict[ele] for ele in test_str.split())
# printing result
print("The string after performing replace : " + res)
#Output : The original string is : zero four zero one
[END] |
Python | Convert numeric words to numbers | https://www.geeksforgeeks.org/python-convert-numeric-words-to-numbers/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Convert numeric words to numbers
# Using word2number
from word2number import w2n
# initializing string
test_str = "zero four zero one"
# printing original string
print("The original string is : " + test_str)
# Convert numeric words to numbers
# Using word2number
res = w2n.word_to_num(test_str)
# printing result
print("The string after performing replace : " + str(res)) |
#Output : The original string is : zero four zero one | Python | Convert numeric words to numbers
# Python3 code to demonstrate working of
# Convert numeric words to numbers
# Using word2number
from word2number import w2n
# initializing string
test_str = "zero four zero one"
# printing original string
print("The original string is : " + test_str)
# Convert numeric words to numbers
# Using word2number
res = w2n.word_to_num(test_str)
# printing result
print("The string after performing replace : " + str(res))
#Output : The original string is : zero four zero one
[END] |
Python | Convert numeric words to numbers | https://www.geeksforgeeks.org/python-convert-numeric-words-to-numbers/?ref=leftbar-rightbar | import re
def convert_to_numbers(s):
words_to_numbers = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"zero": "0",
}
pattern = re.compile(r"\b(" + "|".join(words_to_numbers.keys()) + r")\b")
return re.sub(pattern, lambda x: words_to_numbers[x.group()], s)
# Example usage:
s = "zero four zero one"
print(convert_to_numbers(s)) # Output: "0 4 0 1" |
#Output : The original string is : zero four zero one | Python | Convert numeric words to numbers
import re
def convert_to_numbers(s):
words_to_numbers = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"zero": "0",
}
pattern = re.compile(r"\b(" + "|".join(words_to_numbers.keys()) + r")\b")
return re.sub(pattern, lambda x: words_to_numbers[x.group()], s)
# Example usage:
s = "zero four zero one"
print(convert_to_numbers(s)) # Output: "0 4 0 1"
#Output : The original string is : zero four zero one
[END] |
Python | Convert numeric words to numbers | https://www.geeksforgeeks.org/python-convert-numeric-words-to-numbers/?ref=leftbar-rightbar | # Define a dictionary that maps numeric words to their corresponding digits
word_to_digit = {
"zero": "0",
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
}
# Define the input string
test_str = "zero four zero one"
# Split the input string into words
words = test_str.split()
# Map each word to its corresponding digit using the dictionary
digits = [word_to_digit[word] for word in words]
# Join the resulting list of digits into a string
result = "".join(digits)
# Print the original string and the result
print("The original string is:", test_str)
print("The string after performing replace:", result) |
#Output : The original string is : zero four zero one | Python | Convert numeric words to numbers
# Define a dictionary that maps numeric words to their corresponding digits
word_to_digit = {
"zero": "0",
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
}
# Define the input string
test_str = "zero four zero one"
# Split the input string into words
words = test_str.split()
# Map each word to its corresponding digit using the dictionary
digits = [word_to_digit[word] for word in words]
# Join the resulting list of digits into a string
result = "".join(digits)
# Print the original string and the result
print("The original string is:", test_str)
print("The string after performing replace:", result)
#Output : The original string is : zero four zero one
[END] |
Python | Convert numeric words to numbers | https://www.geeksforgeeks.org/python-convert-numeric-words-to-numbers/?ref=leftbar-rightbar | original_string = "zero four zero one"
result = "".join(
[
"0"
if word == "zero"
else "1"
if word == "one"
else "2"
if word == "two"
else "3"
if word == "three"
else "4"
if word == "four"
else "5"
if word == "five"
else "6"
if word == "six"
else "7"
if word == "seven"
else "8"
if word == "eight"
else "9"
for word in original_string.split()
]
)
print(result) |
#Output : The original string is : zero four zero one | Python | Convert numeric words to numbers
original_string = "zero four zero one"
result = "".join(
[
"0"
if word == "zero"
else "1"
if word == "one"
else "2"
if word == "two"
else "3"
if word == "three"
else "4"
if word == "four"
else "5"
if word == "five"
else "6"
if word == "six"
else "7"
if word == "seven"
else "8"
if word == "eight"
else "9"
for word in original_string.split()
]
)
print(result)
#Output : The original string is : zero four zero one
[END] |
Python | Word location in String | https://www.geeksforgeeks.org/python-word-location-in-string/ | # Python3 code to demonstrate working of
# Word location in String
# Using findall() + index()
import re
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing word
wrd = "best"
# Word location in String
# Using findall() + index()
test_str = test_str.split()
res = -1
for idx in test_str:
if len(re.findall(wrd, idx)) > 0:
res = test_str.index(idx) + 1
# printing result
print("The location of word is : " + str(res)) |
#Output : The original string is : geeksforgeeks is best for geeks | Python | Word location in String
# Python3 code to demonstrate working of
# Word location in String
# Using findall() + index()
import re
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing word
wrd = "best"
# Word location in String
# Using findall() + index()
test_str = test_str.split()
res = -1
for idx in test_str:
if len(re.findall(wrd, idx)) > 0:
res = test_str.index(idx) + 1
# printing result
print("The location of word is : " + str(res))
#Output : The original string is : geeksforgeeks is best for geeks
[END] |
Python | Word location in String | https://www.geeksforgeeks.org/python-word-location-in-string/ | # Python3 code to demonstrate working of
# Word location in String
# Using re.sub() + index()
import re
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing word
wrd = "best"
# Word location in String
# Using re.sub() + index()
res = re.sub("[^\w]", " ", test_str).split()
res = res.index(wrd) + 1
# printing result
print("The location of word is : " + str(res)) |
#Output : The original string is : geeksforgeeks is best for geeks | Python | Word location in String
# Python3 code to demonstrate working of
# Word location in String
# Using re.sub() + index()
import re
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing word
wrd = "best"
# Word location in String
# Using re.sub() + index()
res = re.sub("[^\w]", " ", test_str).split()
res = res.index(wrd) + 1
# printing result
print("The location of word is : " + str(res))
#Output : The original string is : geeksforgeeks is best for geeks
[END] |
Python | Word location in String | https://www.geeksforgeeks.org/python-word-location-in-string/ | # Python3 code to demonstrate working of
# Word location in String
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing word
wrd = "best"
x = test_str.split()
res = x.index(wrd) + 1
# printing result
print("The location of word is : " + str(res)) |
#Output : The original string is : geeksforgeeks is best for geeks | Python | Word location in String
# Python3 code to demonstrate working of
# Word location in String
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing word
wrd = "best"
x = test_str.split()
res = x.index(wrd) + 1
# printing result
print("The location of word is : " + str(res))
#Output : The original string is : geeksforgeeks is best for geeks
[END] |
Python | Word location in String | https://www.geeksforgeeks.org/python-word-location-in-string/ | test_str = "geeksforgeeks is best for geeks"
wrd = "best"
# printing original string
print("The original string is : " + test_str)
if wrd in test_str.split():
res = test_str.split().index(wrd) + 1
else:
res = -1
print("The location of word is : " + str(res))
# This code is contributed by Jyothi pinjala |
#Output : The original string is : geeksforgeeks is best for geeks | Python | Word location in String
test_str = "geeksforgeeks is best for geeks"
wrd = "best"
# printing original string
print("The original string is : " + test_str)
if wrd in test_str.split():
res = test_str.split().index(wrd) + 1
else:
res = -1
print("The location of word is : " + str(res))
# This code is contributed by Jyothi pinjala
#Output : The original string is : geeksforgeeks is best for geeks
[END] |
Python | Word location in String | https://www.geeksforgeeks.org/python-word-location-in-string/ | # Set a test string and the word to be searched
test_str = "geeksforgeeks is best for geeks"
wrd = "best"
# Split the test string into words, create a list of indices where the word appears, and add 1 to each index (to account for 0-based indexing)
indices = [i + 1 for i, word in enumerate(test_str.split()) if word == wrd]
# If the list of indices is not empty, set the result to the first index in the list
# Otherwise, set the result to -1
if indices:
res = indices[0]
else:
res = -1
# Print the result
print("The location of word is : " + str(res)) |
#Output : The original string is : geeksforgeeks is best for geeks | Python | Word location in String
# Set a test string and the word to be searched
test_str = "geeksforgeeks is best for geeks"
wrd = "best"
# Split the test string into words, create a list of indices where the word appears, and add 1 to each index (to account for 0-based indexing)
indices = [i + 1 for i, word in enumerate(test_str.split()) if word == wrd]
# If the list of indices is not empty, set the result to the first index in the list
# Otherwise, set the result to -1
if indices:
res = indices[0]
else:
res = -1
# Print the result
print("The location of word is : " + str(res))
#Output : The original string is : geeksforgeeks is best for geeks
[END] |
Python | Word location in String | https://www.geeksforgeeks.org/python-word-location-in-string/ | # Set a test string and the word to be searched
test_str = "geeksforgeeks is best for geeks"
wrd = "best"
# Split the test string into words
words = test_str.split()
# Iterate over the words to find the index of the first occurrence of the word we are searching for
for i, word in enumerate(words):
if word == wrd:
res = i + 1
break
else:
res = -1
# Print the result
print("The location of word is : " + str(res)) |
#Output : The original string is : geeksforgeeks is best for geeks | Python | Word location in String
# Set a test string and the word to be searched
test_str = "geeksforgeeks is best for geeks"
wrd = "best"
# Split the test string into words
words = test_str.split()
# Iterate over the words to find the index of the first occurrence of the word we are searching for
for i, word in enumerate(words):
if word == wrd:
res = i + 1
break
else:
res = -1
# Print the result
print("The location of word is : " + str(res))
#Output : The original string is : geeksforgeeks is best for geeks
[END] |
Python | Consecutive characters frequency | https://www.geeksforgeeks.org/python-consecutive-characters-frequency/ | # Python3 code to demonstrate working of
# Consecutive characters frequency
# Using list comprehension + groupby()
from itertools import groupby
# initializing string
test_str = "geekksforgggeeks"
# printing original string
print("The original string is : " + test_str)
# Consecutive characters frequency
# Using list comprehension + groupby()
res = [len(list(j)) for _, j in groupby(test_str)]
# printing result
print("The Consecutive characters frequency : " + str(res)) |
#Output : The original string is : geekksforgggeeks | Python | Consecutive characters frequency
# Python3 code to demonstrate working of
# Consecutive characters frequency
# Using list comprehension + groupby()
from itertools import groupby
# initializing string
test_str = "geekksforgggeeks"
# printing original string
print("The original string is : " + test_str)
# Consecutive characters frequency
# Using list comprehension + groupby()
res = [len(list(j)) for _, j in groupby(test_str)]
# printing result
print("The Consecutive characters frequency : " + str(res))
#Output : The original string is : geekksforgggeeks
[END] |
Python | Consecutive characters frequency | https://www.geeksforgeeks.org/python-consecutive-characters-frequency/ | # Python3 code to demonstrate working of
# Consecutive characters frequency
# Using regex
import re
# initializing string
test_str = "geekksforgggeeks"
# printing original string
print("The original string is : " + test_str)
# Consecutive characters frequency
# Using regex
res = [len(sub.group()) for sub in re.finditer(r"(.)\1*", test_str)]
# printing result
print("The Consecutive characters frequency : " + str(res)) |
#Output : The original string is : geekksforgggeeks | Python | Consecutive characters frequency
# Python3 code to demonstrate working of
# Consecutive characters frequency
# Using regex
import re
# initializing string
test_str = "geekksforgggeeks"
# printing original string
print("The original string is : " + test_str)
# Consecutive characters frequency
# Using regex
res = [len(sub.group()) for sub in re.finditer(r"(.)\1*", test_str)]
# printing result
print("The Consecutive characters frequency : " + str(res))
#Output : The original string is : geekksforgggeeks
[END] |
Python | Consecutive characters frequency | https://www.geeksforgeeks.org/python-consecutive-characters-frequency/ | # initializing string
test_str = "geekksforgggeeks"
# printing original string
print("The original string is : " + test_str)
# Consecutive characters frequency using loop
res = []
count = 1
for i in range(len(test_str) - 1):
if test_str[i] == test_str[i + 1]:
count += 1
else:
res.append(count)
count = 1
res.append(count)
# printing result
print("The Consecutive characters frequency : " + str(res)) |
#Output : The original string is : geekksforgggeeks | Python | Consecutive characters frequency
# initializing string
test_str = "geekksforgggeeks"
# printing original string
print("The original string is : " + test_str)
# Consecutive characters frequency using loop
res = []
count = 1
for i in range(len(test_str) - 1):
if test_str[i] == test_str[i + 1]:
count += 1
else:
res.append(count)
count = 1
res.append(count)
# printing result
print("The Consecutive characters frequency : " + str(res))
#Output : The original string is : geekksforgggeeks
[END] |
Python | Consecutive characters frequency | https://www.geeksforgeeks.org/python-consecutive-characters-frequency/ | import itertools
# initializing string
test_str = "geekksforgggeeks"
# printing original string
print("The original string is : " + test_str)
# Consecutive characters frequency
# Using itertools.groupby()
res = [len(list(group)) for key, group in itertools.groupby(test_str)]
# printing result
print("The Consecutive characters frequency : " + str(res)) |
#Output : The original string is : geekksforgggeeks | Python | Consecutive characters frequency
import itertools
# initializing string
test_str = "geekksforgggeeks"
# printing original string
print("The original string is : " + test_str)
# Consecutive characters frequency
# Using itertools.groupby()
res = [len(list(group)) for key, group in itertools.groupby(test_str)]
# printing result
print("The Consecutive characters frequency : " + str(res))
#Output : The original string is : geekksforgggeeks
[END] |
String slicing in Python to rotate a string | https://www.geeksforgeeks.org/string-slicing-python-rotate-string/ | # Function to rotate string left and right by d length
def rotate(input, d):
# slice string in two parts for left and right
Lfirst = input[0:d]
Lsecond = input[d:]
Rfirst = input[0 : len(input) - d]
Rsecond = input[len(input) - d :]
# now concatenate two parts together
print("Left Rotation : ", (Lsecond + Lfirst))
print("Right Rotation : ", (Rsecond + Rfirst))
# Driver program
if __name__ == "__main__":
input = "GeeksforGeeks"
d = 2
rotate(input, d) | #Input : s = "GeeksforGeeks"
d = 2 | String slicing in Python to rotate a string
# Function to rotate string left and right by d length
def rotate(input, d):
# slice string in two parts for left and right
Lfirst = input[0:d]
Lsecond = input[d:]
Rfirst = input[0 : len(input) - d]
Rsecond = input[len(input) - d :]
# now concatenate two parts together
print("Left Rotation : ", (Lsecond + Lfirst))
print("Right Rotation : ", (Rsecond + Rfirst))
# Driver program
if __name__ == "__main__":
input = "GeeksforGeeks"
d = 2
rotate(input, d)
#Input : s = "GeeksforGeeks"
d = 2
[END] |
String slicing in Python to rotate a string | https://www.geeksforgeeks.org/string-slicing-python-rotate-string/ | # Function to rotate string left and right by d length
def rotate(str1, n):
# Create the extended string and index of for rotation
temp = str1 + str1
l1 = len(str1)
l2 = len(temp)
Lfirst = temp[n : l1 + n]
Lfirst = temp[l1 - n : l2 - n]
# now printing the string
print("Left Rotation : ", Lfirst)
print("Right Rotation : ", Lfirst)
# Driver program
if __name__ == "__main__":
input = "GeeksforGeeks"
d = 2
rotate(input, d) | #Input : s = "GeeksforGeeks"
d = 2 | String slicing in Python to rotate a string
# Function to rotate string left and right by d length
def rotate(str1, n):
# Create the extended string and index of for rotation
temp = str1 + str1
l1 = len(str1)
l2 = len(temp)
Lfirst = temp[n : l1 + n]
Lfirst = temp[l1 - n : l2 - n]
# now printing the string
print("Left Rotation : ", Lfirst)
print("Right Rotation : ", Lfirst)
# Driver program
if __name__ == "__main__":
input = "GeeksforGeeks"
d = 2
rotate(input, d)
#Input : s = "GeeksforGeeks"
d = 2
[END] |
String slicing in Python to rotate a string | https://www.geeksforgeeks.org/string-slicing-python-rotate-string/ | from collections import deque
def rotate_string(s, d):
deq = deque(s)
if d > 0:
deq.rotate(-d)
else:
deq.rotate(abs(d))
return "".join(deq)
s = "GeeksforGeeks"
d = 2
left_rotated = rotate_string(s, d)
right_rotated = rotate_string(s, -d)
print("Left Rotation: ", left_rotated)
print("Right Rotation: ", right_rotated) | #Input : s = "GeeksforGeeks"
d = 2 | String slicing in Python to rotate a string
from collections import deque
def rotate_string(s, d):
deq = deque(s)
if d > 0:
deq.rotate(-d)
else:
deq.rotate(abs(d))
return "".join(deq)
s = "GeeksforGeeks"
d = 2
left_rotated = rotate_string(s, d)
right_rotated = rotate_string(s, -d)
print("Left Rotation: ", left_rotated)
print("Right Rotation: ", right_rotated)
#Input : s = "GeeksforGeeks"
d = 2
[END] |
String List slicing in Python to check if a string can become empty by recursive deletion | https://www.geeksforgeeks.org/string-slicing-python-check-string-can-become-empty-recursive-deletion/ | def checkEmpty(input, pattern):
# If both are empty
if len(input) == 0 and len(pattern) == 0:
return "true"
# If only pattern is empty
if len(pattern) == 0:
return "false"
while len(input) != 0:
# find sub-string in main string
index = input.find(pattern)
# check if sub-string founded or not
if index == (-1):
return "false"
# slice input string in two parts and concatenate
input = input[0:index] + input[index + len(pattern) :]
return "true"
# Driver program
if __name__ == "__main__":
input = "GEEGEEKSKS"
pattern = "GEEKS"
print(checkEmpty(input, pattern)) | Input : str = "GEEGEEKSKS", sub_str = "GEEKS"
#Output : Yes | String List slicing in Python to check if a string can become empty by recursive deletion
def checkEmpty(input, pattern):
# If both are empty
if len(input) == 0 and len(pattern) == 0:
return "true"
# If only pattern is empty
if len(pattern) == 0:
return "false"
while len(input) != 0:
# find sub-string in main string
index = input.find(pattern)
# check if sub-string founded or not
if index == (-1):
return "false"
# slice input string in two parts and concatenate
input = input[0:index] + input[index + len(pattern) :]
return "true"
# Driver program
if __name__ == "__main__":
input = "GEEGEEKSKS"
pattern = "GEEKS"
print(checkEmpty(input, pattern))
Input : str = "GEEGEEKSKS", sub_str = "GEEKS"
#Output : Yes
[END] |
Python Program to find minimum number of rotations to obtain actual string | https://www.geeksforgeeks.org/python-program-to-find-minimum-number-of-rotations-to-obtain-actual-string/ | def findRotations(str1, str2):
# To count left rotations
# of string
x = 0
# To count right rotations
# of string
y = 0
m = str1
while True:
# left rotating the string
m = m[len(m) - 1] + m[: len(m) - 1]
# checking if rotated and
# actual string are equal.
if m == str2:
x += 1
break
else:
x += 1
if x > len(str2):
break
while True:
# right rotating the string
str1 = str1[1 : len(str1)] + str1[0]
# checking if rotated and actual
# string are equal.
if str1 == str2:
y += 1
break
else:
y += 1
if y > len(str2):
break
if x < len(str2):
# printing the minimum
# number of rotations.
print(min(x, y))
else:
print("given strings are not of same kind")
# Driver code
findRotations("sgeek", "geeks") | #Input : eeksg, geeks
Output: 1 | Python Program to find minimum number of rotations to obtain actual string
def findRotations(str1, str2):
# To count left rotations
# of string
x = 0
# To count right rotations
# of string
y = 0
m = str1
while True:
# left rotating the string
m = m[len(m) - 1] + m[: len(m) - 1]
# checking if rotated and
# actual string are equal.
if m == str2:
x += 1
break
else:
x += 1
if x > len(str2):
break
while True:
# right rotating the string
str1 = str1[1 : len(str1)] + str1[0]
# checking if rotated and actual
# string are equal.
if str1 == str2:
y += 1
break
else:
y += 1
if y > len(str2):
break
if x < len(str2):
# printing the minimum
# number of rotations.
print(min(x, y))
else:
print("given strings are not of same kind")
# Driver code
findRotations("sgeek", "geeks")
#Input : eeksg, geeks
Output: 1
[END] |
Python - Words Frequency in String Shorthands | https://www.geeksforgeeks.org/python-words-frequency-in-string-shorthands/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
# Initializing string
test_str = "Gfg is best . Geeks are good and Geeks like Gfg"
# Printing original string
print("The original string is : " + str(test_str))
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
res = {key: test_str.count(key) for key in test_str.split()}
# Printing result
print("The words frequency : " + str(res)) | #Input : test_str = 'Gfg is best'
#Output : {'Gfg': 1, 'is': 1, 'best': 1} | Python - Words Frequency in String Shorthands
# Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
# Initializing string
test_str = "Gfg is best . Geeks are good and Geeks like Gfg"
# Printing original string
print("The original string is : " + str(test_str))
# Words Frequency in String Shorthands
# Using dictionary comprehension + count() + split()
res = {key: test_str.count(key) for key in test_str.split()}
# Printing result
print("The words frequency : " + str(res))
#Input : test_str = 'Gfg is best'
#Output : {'Gfg': 1, 'is': 1, 'best': 1}
[END] |
Python - Words Frequency in String Shorthands | https://www.geeksforgeeks.org/python-words-frequency-in-string-shorthands/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using Counter() + split()
from collections import Counter
# initializing string
test_str = "Gfg is best . Geeks are good and Geeks like Gfg"
# printing original string
print("The original string is : " + str(test_str))
# Words Frequency in String Shorthands
# using Counter() + split()
res = Counter(test_str.split())
# Printing result
print("The words frequency : " + str(dict(res))) | #Input : test_str = 'Gfg is best'
#Output : {'Gfg': 1, 'is': 1, 'best': 1} | Python - Words Frequency in String Shorthands
# Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using Counter() + split()
from collections import Counter
# initializing string
test_str = "Gfg is best . Geeks are good and Geeks like Gfg"
# printing original string
print("The original string is : " + str(test_str))
# Words Frequency in String Shorthands
# using Counter() + split()
res = Counter(test_str.split())
# Printing result
print("The words frequency : " + str(dict(res)))
#Input : test_str = 'Gfg is best'
#Output : {'Gfg': 1, 'is': 1, 'best': 1}
[END] |
Python - Words Frequency in String Shorthands | https://www.geeksforgeeks.org/python-words-frequency-in-string-shorthands/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using dictionary comprehension + operator.countOf() + split()
import operator as op
# Initializing string
test_str = "Gfg is best . Geeks are good and Geeks like Gfg"
# Printing original string
print("The original string is : " + str(test_str))
listString = test_str.split()
# Words Frequency in String Shorthands
# Using dictionary comprehension + operator.countOf()
res = {key: op.countOf(listString, key) for key in listString}
# Printing the result
print("The words frequency : " + str(res)) | #Input : test_str = 'Gfg is best'
#Output : {'Gfg': 1, 'is': 1, 'best': 1} | Python - Words Frequency in String Shorthands
# Python3 code to demonstrate working of
# Words Frequency in String Shorthands
# Using dictionary comprehension + operator.countOf() + split()
import operator as op
# Initializing string
test_str = "Gfg is best . Geeks are good and Geeks like Gfg"
# Printing original string
print("The original string is : " + str(test_str))
listString = test_str.split()
# Words Frequency in String Shorthands
# Using dictionary comprehension + operator.countOf()
res = {key: op.countOf(listString, key) for key in listString}
# Printing the result
print("The words frequency : " + str(res))
#Input : test_str = 'Gfg is best'
#Output : {'Gfg': 1, 'is': 1, 'best': 1}
[END] |
Python - Words Frequency in String Shorthands | https://www.geeksforgeeks.org/python-words-frequency-in-string-shorthands/?ref=leftbar-rightbar | from collections import defaultdict
# Initializing string
test_str = "Gfg is best . Geeks are good and Geeks like Gfg"
# Printing original string
print("The original string is : " + str(test_str))
# Split the string into a list of words
listString = test_str.split()
# Creating a defaultdict with default value 0
freq = defaultdict(int)
# Iterating through the list of words and
# count the frequency of each word
for word in listString:
freq[word] += 1
# Converting the defaultdict to a regular dictionary
res = dict(freq)
# Printing result
print("The words frequency : " + str(res)) | #Input : test_str = 'Gfg is best'
#Output : {'Gfg': 1, 'is': 1, 'best': 1} | Python - Words Frequency in String Shorthands
from collections import defaultdict
# Initializing string
test_str = "Gfg is best . Geeks are good and Geeks like Gfg"
# Printing original string
print("The original string is : " + str(test_str))
# Split the string into a list of words
listString = test_str.split()
# Creating a defaultdict with default value 0
freq = defaultdict(int)
# Iterating through the list of words and
# count the frequency of each word
for word in listString:
freq[word] += 1
# Converting the defaultdict to a regular dictionary
res = dict(freq)
# Printing result
print("The words frequency : " + str(res))
#Input : test_str = 'Gfg is best'
#Output : {'Gfg': 1, 'is': 1, 'best': 1}
[END] |
Python - Successive Characters Frequency | https://www.geeksforgeeks.org/python-successive-characters-frequency/ | # Python3 code to demonstrate working of
# Successive Characters Frequency
# Using count() + loop + re.findall()
import re
# initializing string
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
# printing original string
print("The original string is : " + str(test_str))
# initializing word
que_word = "geek"
# Successive Characters Frequency
# Using count() + loop + re.findall()
temp = []
for sub in re.findall(que_word + ".", test_str):
temp.append(sub[-1])
res = {que_word: temp.count(que_word) for que_word in temp}
# printing result
print("The Characters Frequency is : " + str(res)) | #Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}?? | Python - Successive Characters Frequency
# Python3 code to demonstrate working of
# Successive Characters Frequency
# Using count() + loop + re.findall()
import re
# initializing string
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
# printing original string
print("The original string is : " + str(test_str))
# initializing word
que_word = "geek"
# Successive Characters Frequency
# Using count() + loop + re.findall()
temp = []
for sub in re.findall(que_word + ".", test_str):
temp.append(sub[-1])
res = {que_word: temp.count(que_word) for que_word in temp}
# printing result
print("The Characters Frequency is : " + str(res))
#Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}??
[END] |
Python - Successive Characters Frequency | https://www.geeksforgeeks.org/python-successive-characters-frequency/ | # Python3 code to demonstrate working of
# Successive Characters Frequency
# Using Counter() + list comprehension + re.findall()
from collections import Counter
import re
# initializing string
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
# printing original string
print("The original string is : " + str(test_str))
# initializing word
que_word = "geek"
# Successive Characters Frequency
# Using Counter() + list comprehension + re.findall()
res = dict(Counter(re.findall(f"{que_word}(.)", test_str, flags=re.IGNORECASE)))
# printing result
print("The Characters Frequency is : " + str(res)) | #Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}?? | Python - Successive Characters Frequency
# Python3 code to demonstrate working of
# Successive Characters Frequency
# Using Counter() + list comprehension + re.findall()
from collections import Counter
import re
# initializing string
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
# printing original string
print("The original string is : " + str(test_str))
# initializing word
que_word = "geek"
# Successive Characters Frequency
# Using Counter() + list comprehension + re.findall()
res = dict(Counter(re.findall(f"{que_word}(.)", test_str, flags=re.IGNORECASE)))
# printing result
print("The Characters Frequency is : " + str(res))
#Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}??
[END] |
Python - Successive Characters Frequency | https://www.geeksforgeeks.org/python-successive-characters-frequency/ | # Python3 code to demonstrate working of
# Successive Characters Frequency
# Using operator.countOf() + loop + re.findall()
import re
import operator as op
# initializing string
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
# printing original string
print("The original string is : " + str(test_str))
# initializing word
que_word = "geek"
# Successive Characters Frequency
# Using operator.countOf() + loop + re.findall()
temp = []
for sub in re.findall(que_word + ".", test_str):
temp.append(sub[-1])
res = {que_word: op.countOf(temp, que_word) for que_word in temp}
# printing result
print("The Characters Frequency is : " + str(res)) | #Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}?? | Python - Successive Characters Frequency
# Python3 code to demonstrate working of
# Successive Characters Frequency
# Using operator.countOf() + loop + re.findall()
import re
import operator as op
# initializing string
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
# printing original string
print("The original string is : " + str(test_str))
# initializing word
que_word = "geek"
# Successive Characters Frequency
# Using operator.countOf() + loop + re.findall()
temp = []
for sub in re.findall(que_word + ".", test_str):
temp.append(sub[-1])
res = {que_word: op.countOf(temp, que_word) for que_word in temp}
# printing result
print("The Characters Frequency is : " + str(res))
#Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}??
[END] |
Python - Successive Characters Frequency | https://www.geeksforgeeks.org/python-successive-characters-frequency/ | # initializing string
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
# initializing word
que_word = "geek"
# initializing dictionary to store character frequencies
freq_dict = {}
# loop through the string and count successive character frequencies
for i in range(len(test_str) - 1):
if test_str[i : i + len(que_word)] == que_word:
char = test_str[i + len(que_word)]
if char in freq_dict:
freq_dict[char] += 1
else:
freq_dict[char] = 1
# print the result
print("The Characters Frequency is:", freq_dict) | #Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}?? | Python - Successive Characters Frequency
# initializing string
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
# initializing word
que_word = "geek"
# initializing dictionary to store character frequencies
freq_dict = {}
# loop through the string and count successive character frequencies
for i in range(len(test_str) - 1):
if test_str[i : i + len(que_word)] == que_word:
char = test_str[i + len(que_word)]
if char in freq_dict:
freq_dict[char] += 1
else:
freq_dict[char] = 1
# print the result
print("The Characters Frequency is:", freq_dict)
#Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}??
[END] |
Python - Successive Characters Frequency | https://www.geeksforgeeks.org/python-successive-characters-frequency/ | import re
from collections import defaultdict
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
que_word = "geek"
freq_dict = defaultdict(int)
for match in re.finditer(que_word + "(.)", test_str):
freq_dict[match.group(1)] += 1
print("The Characters Frequency is:", dict(freq_dict)) | #Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}?? | Python - Successive Characters Frequency
import re
from collections import defaultdict
test_str = "geeksforgeeks is best for geeks. A geek should take interest."
que_word = "geek"
freq_dict = defaultdict(int)
for match in re.finditer(que_word + "(.)", test_str):
freq_dict[match.group(1)] += 1
print("The Characters Frequency is:", dict(freq_dict))
#Input : test_str = 'geeks are for geeksforgeeks', que_word = "geek"??
#Output : {'s': 3}??
[END] |
Python - Sort String List by K character frequency | https://www.geeksforgeeks.org/python-sort-string-list-by-k-character-frequency/ | # Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sorted() + count() + lambda
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "e"
# "-" sign used to reverse sort
res = sorted(test_list, key=lambda ele: -ele.count(K))
# printing results
print("Sorted String : " + str(res)) |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python - Sort String List by K character frequency
# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sorted() + count() + lambda
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "e"
# "-" sign used to reverse sort
res = sorted(test_list, key=lambda ele: -ele.count(K))
# printing results
print("Sorted String : " + str(res))
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |
Python - Sort String List by K character frequency | https://www.geeksforgeeks.org/python-sort-string-list-by-k-character-frequency/ | # Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sort() + count() + lambda
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "e"
# "-" sign used to reverse sort
# inplace sort
test_list.sort(key=lambda ele: -ele.count(K))
# printing results
print("Sorted String : " + str(test_list)) |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python - Sort String List by K character frequency
# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sort() + count() + lambda
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "e"
# "-" sign used to reverse sort
# inplace sort
test_list.sort(key=lambda ele: -ele.count(K))
# printing results
print("Sorted String : " + str(test_list))
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |
Python - Sort String List by K character frequency | https://www.geeksforgeeks.org/python-sort-string-list-by-k-character-frequency/ | # Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using operator.countOf()
import operator as op
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "e"
# "-" sign used to reverse sort
res = sorted(test_list, key=lambda ele: -op.countOf(ele, K))
# printing results
print("Sorted String : " + str(res)) |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python - Sort String List by K character frequency
# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using operator.countOf()
import operator as op
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "e"
# "-" sign used to reverse sort
res = sorted(test_list, key=lambda ele: -op.countOf(ele, K))
# printing results
print("Sorted String : " + str(res))
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |
Python - Sort String List by K character frequency | https://www.geeksforgeeks.org/python-sort-string-list-by-k-character-frequency/ | import heapq
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# initializing K
K = "e"
# define lambda function to count occurrences of K in a string
count_K = lambda s: s.count(K)
# use nlargest to sort test_list based on count of K in each string
n = len(test_list)
sorted_list = heapq.nlargest(n, test_list, key=count_K)
# use sorted to sort test_list based on count of K in each string
sorted_list = sorted(test_list, key=count_K, reverse=True)
# print results
print("Sorted String: ", sorted_list) |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python - Sort String List by K character frequency
import heapq
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# initializing K
K = "e"
# define lambda function to count occurrences of K in a string
count_K = lambda s: s.count(K)
# use nlargest to sort test_list based on count of K in each string
n = len(test_list)
sorted_list = heapq.nlargest(n, test_list, key=count_K)
# use sorted to sort test_list based on count of K in each string
sorted_list = sorted(test_list, key=count_K, reverse=True)
# print results
print("Sorted String: ", sorted_list)
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |
Python - Convert Snake case to Pascal case | https://www.geeksforgeeks.org/python-convert-snake-case-to-pascal-case/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Convert Snake case to Pascal case
# Using title() + replace()
# initializing string
test_str = "geeksforgeeks_is_best"
# printing original string
print("The original string is : " + test_str)
# Convert Snake case to Pascal case
# Using title() + replace()
res = test_str.replace("_", " ").title().replace(" ", "")
# printing result
print("The String after changing case : " + str(res)) |
#Output : The original string is : geeksforgeeks_is_best | Python - Convert Snake case to Pascal case
# Python3 code to demonstrate working of
# Convert Snake case to Pascal case
# Using title() + replace()
# initializing string
test_str = "geeksforgeeks_is_best"
# printing original string
print("The original string is : " + test_str)
# Convert Snake case to Pascal case
# Using title() + replace()
res = test_str.replace("_", " ").title().replace(" ", "")
# printing result
print("The String after changing case : " + str(res))
#Output : The original string is : geeksforgeeks_is_best
[END] |
Python - Convert Snake case to Pascal case | https://www.geeksforgeeks.org/python-convert-snake-case-to-pascal-case/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Convert Snake case to Pascal case
# Using capwords()
import string
# initializing string
test_str = "geeksforgeeks_is_best"
# printing original string
print("The original string is : " + test_str)
# Convert Snake case to Pascal case
# Using capwords()
res = string.capwords(test_str.replace("_", " ")).replace(" ", "")
# printing result
print("The String after changing case : " + str(res)) |
#Output : The original string is : geeksforgeeks_is_best | Python - Convert Snake case to Pascal case
# Python3 code to demonstrate working of
# Convert Snake case to Pascal case
# Using capwords()
import string
# initializing string
test_str = "geeksforgeeks_is_best"
# printing original string
print("The original string is : " + test_str)
# Convert Snake case to Pascal case
# Using capwords()
res = string.capwords(test_str.replace("_", " ")).replace(" ", "")
# printing result
print("The String after changing case : " + str(res))
#Output : The original string is : geeksforgeeks_is_best
[END] |
Python - Convert Snake case to Pascal case | https://www.geeksforgeeks.org/python-convert-snake-case-to-pascal-case/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Convert Snake case to Pascal case
# initializing string
test_str = "geeksforgeeks_is_best"
# printing original string
print("The original string is : " + test_str)
# Convert Snake case to Pascal case
x = test_str.split("_")
res = []
for i in x:
i = i.title()
res.append(i)
res = "".join(res)
# printing result
print("The String after changing case : " + str(res)) |
#Output : The original string is : geeksforgeeks_is_best | Python - Convert Snake case to Pascal case
# Python3 code to demonstrate working of
# Convert Snake case to Pascal case
# initializing string
test_str = "geeksforgeeks_is_best"
# printing original string
print("The original string is : " + test_str)
# Convert Snake case to Pascal case
x = test_str.split("_")
res = []
for i in x:
i = i.title()
res.append(i)
res = "".join(res)
# printing result
print("The String after changing case : " + str(res))
#Output : The original string is : geeksforgeeks_is_best
[END] |
Python - Convert Snake case to Pascal case | https://www.geeksforgeeks.org/python-convert-snake-case-to-pascal-case/?ref=leftbar-rightbar | def snake_to_pascal_case_1(snake_str):
words = snake_str.split("_")
pascal_str = "".join([word.capitalize() for word in words])
return pascal_str
snake_str = "geeksforgeeks_is_best"
print(snake_to_pascal_case_1(snake_str)) |
#Output : The original string is : geeksforgeeks_is_best | Python - Convert Snake case to Pascal case
def snake_to_pascal_case_1(snake_str):
words = snake_str.split("_")
pascal_str = "".join([word.capitalize() for word in words])
return pascal_str
snake_str = "geeksforgeeks_is_best"
print(snake_to_pascal_case_1(snake_str))
#Output : The original string is : geeksforgeeks_is_best
[END] |
Python - Convert Snake case to Pascal case | https://www.geeksforgeeks.org/python-convert-snake-case-to-pascal-case/?ref=leftbar-rightbar | string = "geeksforgeeks_is_best"
words = string.split("_")
capitalized_words = [word.title() for word in words]
result = "".join(capitalized_words)
print(result) |
#Output : The original string is : geeksforgeeks_is_best | Python - Convert Snake case to Pascal case
string = "geeksforgeeks_is_best"
words = string.split("_")
capitalized_words = [word.title() for word in words]
result = "".join(capitalized_words)
print(result)
#Output : The original string is : geeksforgeeks_is_best
[END] |
Python - Convert Snake case to Pascal case | https://www.geeksforgeeks.org/python-convert-snake-case-to-pascal-case/?ref=leftbar-rightbar | # Python3 code to demonstrate working of
# Convert Snake case to Pascal case using reduce() method
from functools import reduce
# initializing string
test_str = "geeksforgeeks_is_best"
# printing original string
print("The original string is : " + test_str)
# Convert Snake case to Pascal case using reduce() method
res = reduce(lambda a, b: a + b.title(), test_str.split("_"), "")
# printing result
print("The String after changing case : " + str(res))
# This code is contributed by Jyothi pinjala. |
#Output : The original string is : geeksforgeeks_is_best | Python - Convert Snake case to Pascal case
# Python3 code to demonstrate working of
# Convert Snake case to Pascal case using reduce() method
from functools import reduce
# initializing string
test_str = "geeksforgeeks_is_best"
# printing original string
print("The original string is : " + test_str)
# Convert Snake case to Pascal case using reduce() method
res = reduce(lambda a, b: a + b.title(), test_str.split("_"), "")
# printing result
print("The String after changing case : " + str(res))
# This code is contributed by Jyothi pinjala.
#Output : The original string is : geeksforgeeks_is_best
[END] |
Python - Convert Snake case to Pascal case | https://www.geeksforgeeks.org/python-convert-snake-case-to-pascal-case/?ref=leftbar-rightbar | def snake_to_pascal(input_str):
result = ""
capitalize_next_word = True
for char in input_str:
if char == "_":
capitalize_next_word = True
elif capitalize_next_word:
result += char.upper()
capitalize_next_word = False
else:
result += char
return result
# inputs
print(snake_to_pascal("geeks_for_geeks"))
print(snake_to_pascal("left_index")) |
#Output : The original string is : geeksforgeeks_is_best | Python - Convert Snake case to Pascal case
def snake_to_pascal(input_str):
result = ""
capitalize_next_word = True
for char in input_str:
if char == "_":
capitalize_next_word = True
elif capitalize_next_word:
result += char.upper()
capitalize_next_word = False
else:
result += char
return result
# inputs
print(snake_to_pascal("geeks_for_geeks"))
print(snake_to_pascal("left_index"))
#Output : The original string is : geeksforgeeks_is_best
[END] |
Python - Avoid Last occurrence of delimiter | https://www.geeksforgeeks.org/python-avoid-last-occurrence-of-delimitter/ | # Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using map() + join() + str()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# appending delim to join
# will leave stray "$" at end
res = ""
for ele in test_list:
res += str(ele) + "$"
# removing last using slicing
res = res[: len(res) - 1]
# printing result
print("The joined string : " + str(res)) |
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9] | Python - Avoid Last occurrence of delimiter
# Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using map() + join() + str()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# appending delim to join
# will leave stray "$" at end
res = ""
for ele in test_list:
res += str(ele) + "$"
# removing last using slicing
res = res[: len(res) - 1]
# printing result
print("The joined string : " + str(res))
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9]
[END] |
Python - Avoid Last occurrence of delimiter | https://www.geeksforgeeks.org/python-avoid-last-occurrence-of-delimitter/ | # Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using map() + join() + str()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# map extends string conversion logic
res = delim.join(map(str, test_list))
# printing result
print("The joined string : " + str(res)) |
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9] | Python - Avoid Last occurrence of delimiter
# Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using map() + join() + str()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# map extends string conversion logic
res = delim.join(map(str, test_list))
# printing result
print("The joined string : " + str(res))
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9]
[END] |
Python - Avoid Last occurrence of delimiter | https://www.geeksforgeeks.org/python-avoid-last-occurrence-of-delimitter/ | # initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# joining elements using list comprehension and str.join()
res = delim.join([str(ele) for ele in test_list])
# removing last delimiter using string slicing
res = res[:-1]
# printing result
print("The joined string : " + str(res)) |
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9] | Python - Avoid Last occurrence of delimiter
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# joining elements using list comprehension and str.join()
res = delim.join([str(ele) for ele in test_list])
# removing last delimiter using string slicing
res = res[:-1]
# printing result
print("The joined string : " + str(res))
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9]
[END] |
Python - Avoid Last occurrence of delimiter | https://www.geeksforgeeks.org/python-avoid-last-occurrence-of-delimitter/ | from functools import reduce
test_list = [4, 7, 8, 3, 2, 1, 9]
print("The Original List is : " + str(test_list))
delimiter = "$"
res = reduce(lambda x, y: str(x) + delimiter + str(y), test_list)
print("The joined string : " + res) |
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9] | Python - Avoid Last occurrence of delimiter
from functools import reduce
test_list = [4, 7, 8, 3, 2, 1, 9]
print("The Original List is : " + str(test_list))
delimiter = "$"
res = reduce(lambda x, y: str(x) + delimiter + str(y), test_list)
print("The joined string : " + res)
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9]
[END] |
Python - Avoid Last occurrence of delimiter | https://www.geeksforgeeks.org/python-avoid-last-occurrence-of-delimitter/ | # Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using str.rstrip()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# join the list elements using the delimiter
res = delim.join(map(str, test_list))
# remove the last occurrence of delimiter using rstrip()
res = res.rstrip(delim)
# printing result
print("The joined string : " + str(res)) |
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9] | Python - Avoid Last occurrence of delimiter
# Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using str.rstrip()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# join the list elements using the delimiter
res = delim.join(map(str, test_list))
# remove the last occurrence of delimiter using rstrip()
res = res.rstrip(delim)
# printing result
print("The joined string : " + str(res))
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9]
[END] |
Python - Avoid Last occurrence of delimiter | https://www.geeksforgeeks.org/python-avoid-last-occurrence-of-delimitter/ | # Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using a loop and string concatenation
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# loop over the list and concatenate the elements with delimiter
res = ""
for i in range(len(test_list) - 1):
res += str(test_list[i]) + delim
# append the last element to res
res += str(test_list[-1])
# printing result
print("The joined string : " + str(res)) |
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9] | Python - Avoid Last occurrence of delimiter
# Python3 code to demonstrate working of
# Avoid Last occurrence of delimiter
# Using a loop and string concatenation
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# loop over the list and concatenate the elements with delimiter
res = ""
for i in range(len(test_list) - 1):
res += str(test_list[i]) + delim
# append the last element to res
res += str(test_list[-1])
# printing result
print("The joined string : " + str(res))
#Output : The original list is : [4, 7, 8, 3, 2, 1, 9]
[END] |
Python program to find the character position of Kth word from a list of strings | https://www.geeksforgeeks.org/python-program-to-find-the-character-position-of-kth-word-from-a-list-of-strings/ | # Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using enumerate() + list comprehension
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
# getting index of word
res = res[K]
# printing result
print("Index of character at Kth position word : " + str(res)) |
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks'] | Python program to find the character position of Kth word from a list of strings
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using enumerate() + list comprehension
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
# getting index of word
res = res[K]
# printing result
print("Index of character at Kth position word : " + str(res))
#Output : The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
[END] |