Python中求字符串中最长的单词
时间: 2023-04-08 16:05:25 浏览: 253
可以使用split()函数将字符串分割成单词列表,然后遍历列表找到最长的单词即可。以下是示例代码:
```python
def find_longest_word(s):
words = s.split()
longest_word = ""
for word in words:
if len(word) > len(longest_word):
longest_word = word
return longest_word
s = "Python is a powerful and easy-to-learn programming language."
longest_word = find_longest_word(s)
print("The longest word is:", longest_word)
```
输出结果为:
```
The longest word is: programming
```
相关问题
Python求字符串中最长的三个单词
可以先将字符串分割成单词列表,然后对列表进行排序,最后取最长的三个单词即可。代码如下:
```python
def find_longest_words(s):
words = s.split() # 将字符串分割成单词列表
words.sort(key=lambda x: len(x), reverse=True) # 按单词长度降序排序
return words[:3] # 取前三个单词
s = "Python is a powerful programming language that is easy to learn"
print(find_longest_words(s)) # 输出:['programming', 'language', 'powerful']
```
在这个例子中,最长的三个单词是"programming"、"language"和"powerful"。
Python选择结构求字符串中最长的三个单词
可以使用Python的字符串处理和选择结构来解决这个问题。一种可能的方法如下:
1. 将字符串按照空格分割成单词列表。
2. 定义三个变量,分别表示当前最长的三个单词。
3. 遍历单词列表,对于每个单词,比较它的长度和当前最长的三个单词的长度。
4. 如果该单词比当前最长的三个单词中的任何一个都长,则更新最长的三个单词。
5. 最终得到的就是该字符串中最长的三个单词。
以下是具体代码实现:
```python
def find_longest_three_words(s):
words = s.split() # 将字符串按照空格分割成单词列表
longest_1, longest_2, longest_3 = "", "", "" # 定义三个变量,初始值为空字符串
for word in words:
if len(word) > len(longest_1):
longest_1, longest_2, longest_3 = word, longest_1, longest_2
elif len(word) > len(longest_2):
longest_2, longest_3 = word, longest_2
elif len(word) > len(longest_3):
longest_3 = word
return [longest_1, longest_2, longest_3]
```
这个函数接受一个字符串参数,返回一个包含最长的三个单词的列表。