In this tutorial, we'll write a Python program to split each word in a string according to a given percentage.
Objective: We want to split each word in a string such that the first part contains a given percentage of the word and the second part contains the rest.
Example:
Input String: "Python" Percentage: 30% (or 0.3 in decimal form) Output: ['Pyt', 'hon']
Step-by-step Solution:
Step 1: Define the input string and percentage.
input_string = "Python" percentage = 0.3
Step 2: Write a function to split a word according to the percentage.
def split_word(word, percentage): split_index = int(len(word) * percentage) return [word[:split_index], word[split_index:]]
Step 3: Split each word in the input string.
First, split the input string into words. Then, apply the split_word
function to each word.
words = input_string.split() result = [split_word(word, percentage) for word in words]
Step 4: Display the result.
for word_pair in result: print(word_pair)
Complete Program:
def split_word(word, percentage): split_index = int(len(word) * percentage) return [word[:split_index], word[split_index:]] # Define the input string and percentage input_string = "Python Programming is fun" percentage = 0.3 # Split each word in the input string words = input_string.split() result = [split_word(word, percentage) for word in words] # Display the result for word_pair in result: print(word_pair)
Output:
['Pyt', 'hon'] ['Pro', 'gramming'] ['is', ''] ['fu', 'n']
Note:
30%
would be 0.3
. Adjust the percentage as needed.angular-data divide-and-conquer minify heatmap statsmodels crontrigger amazon-rekognition phantomjs postback ef-core-2.1