📜  Python|提取字符串中的奇数长度单词

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

Python|提取字符串中的奇数长度单词

有时,在使用Python时,我们可能会遇到需要从字符串中提取特定长度单词的问题。这可以从字符串中提取奇数长度的单词。这可以在包括日间编程在内的许多领域中得到应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们首先将字符串拆分为单词,然后执行迭代以获得奇数长度的单词。

# Python3 code to demonstrate working of 
# Extract odd length words in String
# Using loop
  
# initializing string
test_str = "gfg is best of geeks"
  
# printing original string
print("The original string is : " + test_str)
  
# Extract odd length words in String
# Using loop
res = []
for ele in test_str.split():
    if len(ele) % 2 :
        res.append(ele)
  
# printing result 
print("The odd length strings are : " + str(res)) 
输出 :
The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']

方法#2:使用列表推导
也可以使用列表推导来执行此任务。在此,我们以与上述类似的方式执行任务。只是不同之处在于它是单线的。

# Python3 code to demonstrate working of 
# Extract odd length words in String
# Using list comprehension
  
# initializing string
test_str = "gfg is best of geeks"
  
# printing original string
print("The original string is : " + test_str)
  
# Extract odd length words in String
# Using list comprehension
res = [ele for ele in test_str.split() if len(ele) % 2]
  
# printing result 
print("The odd length strings are : " + str(res)) 
输出 :
The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']