Python程序去除字符串中K个长度的单词
给定一个字符串,编写一个Python程序来删除所有长度为 K 的单词。
例子:
Input : test_str = ‘Gfg is best for all geeks’, K = 3
Output : is best geeks
Explanation : Gfg, for and all are of length 3, hence removed.
Input : test_str = ‘Gfg is best for all geeks’, K = 2
Output : Gfg best for all geeks
Explanation : is of length 2, hence removed.
方法 #1:使用split() + join() +列表推导+ len()
在这个过程中,每个单词使用 split() 进行拆分,然后使用 len() 检查长度,然后省略匹配 K。最后连接单词。
Python3
# Python3 code to demonstrate working of
# Remove K length words in String
# Using split() + join() + list comprehension + len()
# initializing string
test_str = 'Gfg is best for all geeks'
# printing original string
print("The original string is : " + (test_str))
# initializing K
K = 3
# getting splits
temp = test_str.split()
# omitting K lengths
res = [ele for ele in temp if len(ele) != K]
# joining result
res = ' '.join(res)
# printing result
print("Modified String : " + (res))
Python3
# Python3 code to demonstrate working of
# Remove K length words in String
# Using filter() + lambda + split() + len() + join()
# initializing string
test_str = 'Gfg is best for all geeks'
# printing original string
print("The original string is : " + (test_str))
# initializing K
K = 3
# getting splits
temp = test_str.split()
# omitting K lengths
# filtering using filter() and lambda
res = list(filter(lambda ele: len(ele) != K, temp))
# joining result
res = ' '.join(res)
# printing result
print("Modified String : " + (res))
输出:
The original string is : Gfg is best for all geeks
Modified String : is best geeks
方法#2:使用filter() + lambda + split() + len() + join()
在此,我们使用 filter() + lamnda 执行过滤任务,其余功能与上述方法类似。
蟒蛇3
# Python3 code to demonstrate working of
# Remove K length words in String
# Using filter() + lambda + split() + len() + join()
# initializing string
test_str = 'Gfg is best for all geeks'
# printing original string
print("The original string is : " + (test_str))
# initializing K
K = 3
# getting splits
temp = test_str.split()
# omitting K lengths
# filtering using filter() and lambda
res = list(filter(lambda ele: len(ele) != K, temp))
# joining result
res = ' '.join(res)
# printing result
print("Modified String : " + (res))
输出:
The original string is : Gfg is best for all geeks
Modified String : is best geeks