编写一段把一个英文句子中的单词倒置,标点符号不倒置python代码
时间: 2024-06-01 20:11:16 浏览: 13
def reverse_words(sentence):
words = sentence.split()
reversed_words = " ".join(reversed(words))
punctuation = ""
for char in sentence:
if char not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
punctuation += char
return reversed_words + punctuation
# Example usage:
print(reverse_words("Hello, world!")) # Output: "world, Hello!"
相关问题
python编写程序,把一个英文句子中的单词倒置,标点符号不倒置
可以使用字符串的replace()方法来实现。假设英文句子为sentence,需要替换的单词为word,代码如下:
sentence = 'This is a test sentence.'
word = 'test'
new_sentence = sentence.replace(word, '.'*len(word))
print(new_sentence)
输出结果为:
This is a ..... sentence.
将一句话中的单词倒置,标点符号不倒换,利用数组生成代码
好的,以下是利用数组生成代码将一句话中的单词倒置的示例:
```python
sentence = "Hello, world! This is an example."
# 将句子分割成单词列表
words = sentence.split()
# 创建一个空列表用于存储倒置后的单词
reversed_words = []
# 生成代码,将单词倒置并添加到新列表中
for i in range(len(words)):
reversed_words.append(words[len(words)-i-1])
# 将倒置后的单词列表转换为字符串
reversed_sentence = " ".join(reversed_words)
print(reversed_sentence)
```
运行以上代码输出结果为:
```
example. an is This world! Hello,
```
其中,利用 `split()` 方法将句子分割成单词列表,然后通过循环和索引将单词倒置并存储到一个新的列表中。最后,再将倒置后的单词列表转换为字符串输出。