Saturday, November 23, 2024
Google search engine
HomeLanguagesPython Program to Split each word according to given percent

Python Program to Split each word according to given percent

Given Strings with words, the task is to write a Python program to split each word into two halves on the basis of assigned percentages according to the given values.

Example:

Input : test_str = ‘neveropen is best for all Lazyroar and cs students’, per_splt = 50
Output : Lazyroarf orLazyroar i s be st f or a ll ge eks a nd c s stud ents 
Explanation : Each word after splitting by 50 percent, result is output.

Input : test_str = ‘neveropen is best for all Lazyroar and cs students’, per_splt = 70
Output : Lazyroarforg eeks i s be st fo r al l gee ks an d c s stude nts 
Explanation : Each word after splitting by 70 percent, result is output.

Method 1: Using split() + len() + slice + join()

In this, we split each word and perform a percentage split of each word using len() and slicing. The result is joined in an intermediate fashion using a loop.

Python3




# Python3 code to demonstrate working of
# Split each word into percent segment in list
# Using split() + len() + slice + loop
 
# initializing string
test_str = 'neveropen is best for all Lazyroar and cs students'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing percent split
per_splt = 50
 
test_str = test_str.split()
res = ''
for ele in test_str:
    prop = int((per_splt/100) * len(ele))
    new_str1 = ele[:prop]
    new_str2 = ele[prop:]
    res += new_str1 + " " + new_str2 + " "
     
# printing result
print("Segmented words : " + str(res))


Output:

The original string is : neveropen is best for all Lazyroar and cs students

Segmented words : Lazyroarf orLazyroar i s be st f or a ll ge eks a nd c s stud ents 

Method 2: Using join() 

Similar to the above method, the difference is that join() is used to concatenate the resultant string.

Python3




# Python3 code to demonstrate working of
# Split each word into percent segment in list
# Using join()
 
# initializing string
test_str = 'neveropen is best for all Lazyroar and cs students'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing percent split
per_splt = 50
 
test_str = test_str.split()
 
# one liner solution using join()
res = ' '.join([ele[:int((per_splt/100) * len(ele))]
                + " " + ele[int((per_splt/100) * len(ele)):]
                for ele in test_str])
 
# printing result
print("Segmented words : " + str(res))


Output:

The original string is : neveropen is best for all Lazyroar and cs students

Segmented words : Lazyroarf orLazyroar i s be st f or a ll ge eks a nd c s stud ents 

Time Complexity: O(n)
Auxiliary Space: O(n)

Approach 3: Using regular expressions

In this approach, we use the power of regular expressions to split the words.

Python3




# Python3 code to demonstrate working of
# Split each word into percent segment in list
# Using regular expressions
  
# importing module
import re
  
# initializing string
test_str = 'neveropen is best for all Lazyroar and cs students'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing percent split
per_splt = 50
  
# one liner solution using join()
res = ' '.join([re.sub(r'(\w{' + str(int((per_splt/100) * len(ele))) + r'})(\w+)',
                    r'\1 \2', ele)
                for ele in test_str.split()])
  
# printing result
print("Segmented words : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original string is : neveropen is best for all Lazyroar and cs students
Segmented words : Lazyroarf orLazyroar i s be st f or a ll ge eks a nd c s stud ents

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using the itertools module.

Step-by-step approach:

  1. Import the itertools module.
  2. Split the input string into words using the split() method and store it in a variable.
  3. Loop through each word in the variable created in step 2.
  4. Find the length of the word using the len() method and calculate the number of characters required for the segment using the percent split.
  5. Use the itertools module to split the word into segments of the desired length.
  6. Convert the iterator to a list and join the segments with a space in between.
  7. Append the segmented word to a list.
  8. Join the segmented words in the list with a space and return the segmented string.

Python3




# import itertools module
import itertools
 
# initializing string
test_str = 'neveropen is best for all Lazyroar and cs students'
 
# initializing percent split
per_splt = 50
 
# function to split each word into percent segment
def segment_words(test_str, per_splt):
    # initialize list to store segmented words
    segmented_list = []
    # split string into words
    words = test_str.split()
    # loop through each word
    for word in words:
        # calculate number of characters required for segment
        seg_length = int((per_splt / 100) * len(word))
        # split word into segments of desired length using itertools
        segments = itertools.zip_longest(*[iter(word)]*seg_length, fillvalue='')
        # join segments with space in between
        segmented_word = ' '.join([''.join(segment) for segment in segments])
        # append segmented word to list
        segmented_list.append(segmented_word)
    # join segmented words in list and return segmented string
    return ' '.join(segmented_list)
 
# call function and print result
print("Segmented words : " + segment_words(test_str, per_splt))


Output

Segmented words : Lazyroarf orgeek s i s be st f o r a l l ge ek s a n d c s stud ents

Time complexity: O(nm), where n is the number of words in the input string and m is the length of the longest word.
Auxiliary space: O(nm), where n is the number of words in the input string and m is the length of the longest word.

Method 5: Use the textwrap module:

Step-by-step approach:

  • Import the textwrap module.
  • Define the segment_words function that takes test_str and per_splt as input.
  • Initialize an empty list segmented_list to store the segmented words.
  • Split the input string test_str into individual words and store them in words.
  • Loop through each word in words.
  • Calculate the desired segment length seg_length as a percentage of the length of the current word.
  • Use the textwrap.wrap function to split the word into segments of desired length.
  • Join the segments with a space in between to form the segmented word.
  • Append the segmented word to segmented_list.
  • Join the segmented words in segmented_list with a space in between and return the resulting segmented string.

Python3




import textwrap
 
def segment_words(test_str, per_splt):
    segmented_list = []
    words = test_str.split()
    for word in words:
        seg_length = int((per_splt / 100) * len(word))
        segments = textwrap.wrap(word, seg_length)
        segmented_word = ' '.join(segments)
        segmented_list.append(segmented_word)
    return ' '.join(segmented_list)
 
test_str = 'neveropen is best for all Lazyroar and cs students'
per_splt = 50
segmented_str = segment_words(test_str, per_splt)
print(segmented_str)


Output

Lazyroarf orgeek s i s be st f o r a l l ge ek s a n d c s stud ents

Time complexity: O(n*k), where n is the number of words in the input string and k is the length of the longest word in the input string.
Auxiliary space: O(n*k), where n is the number of words in the input string and k is the length of the longest word in the input string.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments