Python program to convert String to K sized Numerical Rows
Last Updated :
18 Apr, 2023
Given a string of alphabets, convert it to K sized numerical rows, which contain the number being the positional value of characters.
Input : test_str = 'geeksforgeek', K = 4
Output : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10]]
Explanation : g is at 6th position in alphabet hence g→ 6 and the string is split after every fourth character
Input : test_str = 'geeksforgeek', K = 3
Output : [[6, 4, 4], [10, 18, 5], [14, 17, 6], [4, 4, 10]]
Explanation : g is at 6th position in alphabet hence g→ 6 and the string is split after every third character
Method 1 : Using loop + index()
In this, we perform an iteration of each character using a loop and fetch the required position of the character in alphabets using index() on an ordered character list.
Python3
# initializing string
test_str = 'geeksforgeekscse'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
alphabs = "abcdefghijklmnopqrstuvwxyz"
res = []
temp = []
for ele in test_str:
# finding numerical position using index()
temp.append(alphabs.index(ele))
# regroup on K
if len(temp) == K:
res.append(temp)
temp = []
# appending remaining characters
if temp != []:
res.append(temp)
# printing result
print("Grouped and Converted String : " + str(res))
Output:
The original string is : geeksforgeekscse Grouped and Converted String : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10], [18, 2, 18, 4]]
Method #2 : Using ljust() + ord() + list comprehension
In this, we perform the task of padding is required to have equal length rows using ljust(), then get numerical alphabetic positions using ord(), list comprehension with slicing helps to convert the list to K chunked Matrix.
Python3
from math import ceil
# initializing string
test_str = 'geeksforgeekscse'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# filling the rear to K size rows
temp = test_str.ljust(ceil(len(test_str) / K) * K)
# convert to numerical characters
temp = [0 if char == ' ' else (ord(char) - 97) for char in temp]
# slice and render to matrix
res = [temp[idx: idx + K] for idx in range(0, len(temp), K)]
# printing result
print("Grouped and Converted String : " + str(res))
Output:
The original string is : geeksforgeekscse Grouped and Converted String : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10], [18, 2, 18, 4]]
Time Complexity: O(n)
Space Complexity: O(n)
Method 3: Using dictionary
In this method, we use a dictionary to store the alphabet and its corresponding numerical value. Then we loop through the string and convert each character to its corresponding numerical value using the dictionary.
Python3
#initializing string
test_str = 'geeksforgeekscse'
#printing original string
print("The original string is : " + str(test_str))
#initializing K
K = 4
#creating a dictionary for alphabets and their corresponding numerical values
alphabet_dict = {chr(i): i-97 for i in range(97, 123)}
#converting characters to their corresponding numerical values
temp = [alphabet_dict[ele] for ele in test_str]
#slicing the list into K sized sublists
res = [temp[i:i+K] for i in range(0, len(temp), K)]
#printing result
print("Grouped and Converted String : " + str(res))
OutputThe original string is : geeksforgeekscse
Grouped and Converted String : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10], [18, 2, 18, 4]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4 : using the built-in zip() function
Step-by-step approach:
- Initialize the string test_str.
- Print the original string.
- Initialize the value of K.
- Create a list comprehension that converts each character in the string to its corresponding numerical value using the dictionary alphabet_dict.
- Use the zip() function to group the list into K-sized sublists.
- Print the resulting list.
Below is the implementation of the above approach:
Python3
# initializing string
test_str = 'geeksforgeekscse'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# creating a dictionary for alphabets and their corresponding numerical values
alphabet_dict = {chr(i): i-97 for i in range(97, 123)}
# converting characters to their corresponding numerical values
temp = [alphabet_dict[ele] for ele in test_str]
# grouping the list into K-sized sublists using the zip() function
res = [temp[i:i+K] for i in range(0, len(temp), K)]
# printing result
print("Grouped and Converted String : " + str(res))
OutputThe original string is : geeksforgeekscse
Grouped and Converted String : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10], [18, 2, 18, 4]]
Time complexity: O(n), where n is the length of the input string test_str, as we need to iterate through the string to convert each character to its corresponding numerical value, and then group them into sublists.
Auxiliary space: O(n), as we need to store the converted numerical values in a temporary list temp, which has the same length as the input string test_str, and also the resulting list res.
Similar Reads
Python Program to Convert Matrix to String Program converts a 2D matrix (list of lists) into a single string, where all the matrix elements are arranged in row-major order. The elements are separated by spaces or any other delimiter, making it easy to represent matrix data as a string.Using List ComprehensionList comprehension provides a con
2 min read
Python Program to split string into k sized overlapping strings Given a string, the task is to write a Python program to extract overlapping consecutive string slices from the original string according to size K. Example: Input : test_str = 'Geeksforgeeks', K = 4 Output : ['Geek', 'eeks', 'eksf', 'ksfo', 'sfor', 'forg', 'orge', 'rgee', 'geek', 'eeks'] Explanati
4 min read
Python program to get all possible slices of a string for K number of slices Given a string, the task is to write a Python program to get all possible slices for K number of slices. Input : test_str = "Gfg4all", K = 3Output : [['G', 'f', 'g4all'], ['G', 'fg', '4all'], ['G', 'fg4', 'all'], ['G', 'fg4a', 'll'], ['G', 'fg4al', 'l'], ['Gf', 'g', '4all'], ['Gf', 'g4', 'all'], ['G
4 min read
Python | Sort Numerical Records in String Sometimes, while working with Python records we can have a problem that they may occur in name and number format in strings. These may be required to be sorted. This problem can occur in many domains in which data is involved. Let us discuss certain ways in which this task can be performed. Method #
6 min read
Python - Convert String to matrix having K characters per row Given a String, convert it to Matrix, having K characters in each row. Input : test_str = 'GeeksforGeeks is best', K = 7 Output : [['G', 'e', 'e', 'k', 's', 'f', 'o'], ['r', 'G', 'e', 'e', 'k', 's', ' '], ['i', 's', ' ', 'b', 'e', 's', 't']] Explanation : Each character is assigned to 7 element row
9 min read