python单词反转
时间: 2024-01-18 10:18:24 浏览: 256
以下是三种用Python进行单词反转的方法:
方法一:使用split()和join()函数
```python
def reverse_words(str):
words = str.split(' ')
reversed_words = [word[::-1] for word in words]
reversed_str = ' '.join(reversed_words)
return reversed_str
sentence = "Hello World"
reversed_sentence = reverse_words(sentence)
print(reversed_sentence) # 输出:olleH dlroW
```
方法二:使用reversed()函数
```python
def reverse_words(str):
words = str.split(' ')
reversed_words = [word[::-1] for word in words]
reversed_str = ' '.join(reversed(reversed_words))
return reversed_str
sentence = "Hello World"
reversed_sentence = reverse_words(sentence)
print(reversed_sentence) # 输出:olleH dlroW
```
方法三:使用while循环
```python
def reverse_words(str):
words = str.split(' ')
reversed_words = []
i = len(words) - 1
while i >= 0:
reversed_words.append(words[i][::-1])
i -= 1
reversed_str = ' '.join(reversed_words)
return reversed_str
sentence = "Hello World"
reversed_sentence = reverse_words(sentence)
print(reversed_sentence) # 输出:olleH dlroW
```
阅读全文