在Python中迭代字符串的单词
给定一个由空格分隔的多个单词组成的字符串,编写一个Python程序来遍历字符串中的这些单词。
例子:
Input: str = “GeeksforGeeks is a computer science portal for Geeks”
Output:
GeeksforGeeks
is
a
computer
science
portal
for
Geeks
Input: str = “Geeks for Geeks”
Output:
Geeks
for
Geeks
方法一:使用split()
使用split()
函数,我们可以将字符串拆分为单词列表,如果希望完成此特定任务,这是最通用和推荐的方法。但缺点是在字符串中包含标点符号的情况下它会失败。
# Python3 code to demonstrate
# to extract words from string
# using split()
# initializing string
test_string = "GeeksforGeeks is a computer science portal for Geeks"
# printing original string
print ("The original string is : " + test_string)
# using split()
# to extract words from string
res = test_string.split()
# printing result
print ("\nThe words of string are")
for i in res:
print(i)
输出:
The original string is : GeeksforGeeks is a computer science portal for Geeks
The words of string are
GeeksforGeeks
is
a
computer
science
portal
for
Geeks
方法 2:使用re.findall()
在包含所有特殊字符和标点符号的情况下,如上所述,使用拆分在字符串中查找单词的传统方法可能会失败,因此需要正则表达式来执行此任务。 findall()
函数在过滤字符串并提取忽略标点符号的单词后返回列表。
# Python3 code to demonstrate
# to extract words from string
# using regex( findall() )
import re
# initializing string
test_string = "GeeksforGeeks is a computer science portal for Geeks !!!"
# printing original string
print ("The original string is : " + test_string)
# using regex( findall() )
# to extract words from string
res = re.findall(r'\w+', test_string)
# printing result
print ("\nThe words of string are")
for i in res:
print(i)
输出:
The original string is : GeeksforGeeks is a computer science portal for Geeks!!!
The words of string are
GeeksforGeeks
is
a
computer
science
portal
for
Geeks