📜  Python程序根据给定的百分比拆分每个单词

📅  最后修改于: 2022-05-13 01:55:40.250000             🧑  作者: Mango

Python程序根据给定的百分比拆分每个单词

给定带有单词的字符串,任务是编写一个Python程序,根据给定的值根据指定的百分比将每个单词分成两半。

例子:

方法一:使用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))


输出:

方法 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))

输出: