输入一段全英文句子,求其中最长的英文单词及其长度python
时间: 2024-10-15 16:24:13 浏览: 23
To find the longest English word and its length in a Python sentence, you can use the `split()` function to split the input string into words, then iterate through them, checking their length using the `len()` function. Here's a simple example:
```python
def find_longest_word(sentence):
# Split the sentence into words
words = sentence.split()
# Initialize variables for longest word and its length
longest_word = ""
max_length = 0
# Iterate over the words
for word in words:
# Check if current word is longer than the previous longest
if len(word) > max_length and all(c.isalpha() or c.isspace() for c in word): # Only consider alphabetic words
longest_word = word
max_length = len(word)
return longest_word, max_length
# Example usage
sentence = "This is a sample sentence with some long words like 'programming', for instance."
longest_word, word_length = find_longest_word(sentence)
print(f"The longest word is '{longest_word}' and its length is {word_length}.")
阅读全文