python编写程序,把一个英文句子中的单词倒置,标点符号不倒置
时间: 2023-06-05 10:47:31 浏览: 194
可以使用字符串的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的实现代码:
```python
def reverse_words(sentence):
# 将句子按照空格分割成单词列表
words = sentence.split(' ')
# 对单词列表进行倒置
words.reverse()
# 将倒置后的单词列表重新组成一个句子
reversed_sentence = ' '.join(words)
return reversed_sentence
```
使用方法:
```python
sentence = "Hello world, I am a chatbot."
reversed_sentence = reverse_words(sentence)
print(reversed_sentence)
```
输出结果:
```
chatbot. a am I world, Hello
```
将一句话中的单词倒置,标点符号不倒换,利用数组生成代码
好的,以下是利用数组生成代码将一句话中的单词倒置的示例:
```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()` 方法将句子分割成单词列表,然后通过循环和索引将单词倒置并存储到一个新的列表中。最后,再将倒置后的单词列表转换为字符串输出。