Python 打印字符串中长度为偶数的单词

Python 打印字符串中长度为偶数的单词

在Python编程语言中,长度是指从字符串的第一个字符到字符串的最后一个字符之间的范围的概念。在字符串中打印和计算偶数长度是编程语言中的基本练习。

在本教程中,我们将学习查找字符串中所有长度为偶数的单词的解决方案和方法。如果一个数字能够整除2,即不留下余数,那么它被视为奇数。这个特性应适用于我们所需要的单词的长度。因此,程序的目标是只打印长度为偶数的单词,并跳过所有不满足上述属性的单词。

例如,如果我们有一个字符串“一个大的立方体被发现在盒子里。”,对于这个字符串,我们的程序应该只打印单词:”立方体”和”盒子里”,因为这些单词的长度分别是4和6。

方法

  • 使用 str.split() 函数将字符串拆分为单词。

  • 通过单词进行迭代。

  • 使用 len() 函数计算单词的长度。

  • 如果长度为偶数,则打印该单词。

  • 否则不做任何操作。

str.split()

这是Python中适用于字符串的内置函数。使用该函数可以根据指定的分隔符或空格(如果未指定分隔符)拆分字符串。

在Python解释器中使用该函数的帮助命令返回以下信息-

split(self, /, sep=None, maxsplit=-1)
   Return a list of the words in the string, using ‘sep’ as the delimiter string.
   sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.
      maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.

len()

len()是Python中最常用的函数,用于计算Python中任何数据对象中的字符或元素的数量。例如,对于字符串“aaa”,len(“aaa”)将返回3。

从Python解释器的内置帮助中得知 −

len(obj, /)
   Return the number of items in a container.
For a string, its wrapper str.__len__() is called.

示例

在下面的示例中,我们实现了上述方法。我们创建了一个函数来过滤掉字符串中所有长度为偶数的单词。

def printEvenLengthWords(s):
   # splitting the words in a given string
   words = s.split() # same as s.split(' ')
   for word in words:

      # checking the length of words
      if len(word) % 2 == 0:
         print(word)

# input string
sample = 'this is a test string'

# calling the function
printEvenLengthWords(sample)

输出

this
is      
test    
string

一个小的Python额外奖励

Python包含一个内置的名为filter()的函数,它返回一个迭代器。

它接受两个参数,第一个是一个布尔函数,第二个是应用该函数的可迭代对象。我们可以用上述任何方法作为这个函数。

当使用filter()时需要特别小心,因为它是可枯竭的,意味着一旦被使用,无论是用于遍历还是转换为列表,如果再次遍历,则会返回None,因此最好将其转换为列表并存储在另一个变量中。

语法

evenWords = filter(lambda x: len(x) % 2 == 0, 'this is a test string'.split())

示例

def printEvenLengthWords(s):
   # splitting the words in a given string
   words = s.split() # same as s.split(' ')

   # checking the length of words
   evenWords = filter(lambda x: len(x) % 2 == 0, words)

   for word in evenWords:
      print(word)
# calling the function with input string passed in directly
printEvenLengthWords('this is a test string')

输出

this
is      
test    
string

在上面的示例中,lambda 函数的参数 ‘x’ 取代了 split 函数返回的每一个元素。它的工作方式与 for 循环非常相似,但是是一种简短的 Python 方式。

使用 filter() 和列表解析的 Python 单行代码

我们可以直接在 filter 对象上调用 print() 函数,并设置一个可选参数 ‘sep’ 为 ‘\n’ 或换行符。以 ‘*’ 开头表示解压缩可迭代对象并打印全部内容,分隔符以新行的形式打印它们。可以按照以下方式完成。

使用 Lambda 表达式

def printEvenLengthWords(s):
   # please note that one liners are hard to understand
   # and may be frowned upon in some cases
   print(*filter(lambda x: len(x) % 2 == 0, s.split()), sep='\n')

使用列表推导

def printEvenLengthWords(s):
   print(*[x for x in s.split() if len(x) % 2 == 0], sep='\n')

# input string
sample = 'this is a test string'

# calling the function
printEvenLengthWords(sample)    

输出

this
is      
test    
string

注意

使用 split() 函数时,对于以句号(.)结尾的多个语句,句号也会被计算为最后一个单词的一部分。

示例

x = 'Example statement 1. Some line 2.'

当将上述字符串传递给函数时,它也会包括“1.”和“2.”。

输出

1.
Some    
line    
2.

这可以通过一个简单的方法来解决。我们可以使用replace()函数将所有的句号删除,如下所示:

x = 'Example statement 1. Some line 2.'
x = x.replace('.', '')

示例

def printEvenLengthWords(s):
   # handle full stops
   s = s.replace('.', '')

   # splitting the words in a given string
   words = s.split()  # same as s.split(' ')

   for word in words:
      # checking the length of words
      if len(word) % 2 == 0:
         print(word)

# input string
sample = 'Example statement 1. Some line 2.'

# calling the function
printEvenLengthWords(sample)

输出

Some    
line

但应注意,它将删除句子中间的句号,为了更可靠的替代方案,可以使用正则表达式模式。

正则表达式模式

示例

w\.(\s[A-Z])?

这个正则表达式检查是否有任何单词字符后面跟着一个句号,然后要么字符串终止,要么一个新的句子以大写字母开头。正则表达式的更深入学习可以在其他教程中了解。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程