Python程序根据给定的百分比拆分每个单词
给定带有单词的字符串,任务是编写一个Python程序,根据给定的值根据指定的百分比将每个单词分成两半。
例子:
Input : test_str = ‘geeksforgeeks is best for all geeks and cs students’, per_splt = 50
Output : geeksf orgeeks 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 = ‘geeksforgeeks is best for all geeks and cs students’, per_splt = 70
Output : geeksforg 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.
方法一:使用split() + len() + slice + join()
在此,我们拆分每个单词并使用 len() 和切片对每个单词执行百分比拆分。结果使用循环以中间方式连接。
Python3
# Python3 code to demonstrate working of
# Split each word into percent segment in list
# Using split() + len() + slice + loop
# initializing string
test_str = 'geeksforgeeks is best for all geeks 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))
Python3
# Python3 code to demonstrate working of
# Split each word into percent segment in list
# Using join()
# initializing string
test_str = 'geeksforgeeks is best for all geeks 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))
输出:
The original string is : geeksforgeeks is best for all geeks and cs students
Segmented words : geeksf orgeeks i s be st f or a ll ge eks a nd c s stud ents
方法 2:使用 join()
与上述方法类似,不同之处在于 join() 用于连接结果字符串。
蟒蛇3
# Python3 code to demonstrate working of
# Split each word into percent segment in list
# Using join()
# initializing string
test_str = 'geeksforgeeks is best for all geeks 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))
输出:
The original string is : geeksforgeeks is best for all geeks and cs students
Segmented words : geeksf orgeeks i s be st f or a ll ge eks a nd c s stud ents