Python将一段话中的标点替换成空格、
时间: 2024-04-28 13:03:29 浏览: 23
可以使用Python中的字符串替换函数(replace),代码如下:
```python
text = "Hello, World! This is a sentence."
clean_text = text.replace(",", " ").replace(".", " ").replace("!", " ") # 将逗号、句号、感叹号都替换成空格
print(clean_text)
```
输出结果为:
```
Hello World This is a sentence
```
相关问题
用Python写一个程序,实现输入一段字符串,将其中的标点符号替换为空格,然后输出
下面是Python程序的代码实现:
```
text = input("请输入一段字符串:")
for c in "',.;:!?(){}[]":
text = text.replace(c, " ")
print(text)
```
这段程序首先获取用户输入的字符串,然后使用for循环逐个替换字符串中的标点符号为一个空格。最后将处理后的字符串输出。
如何把文本中的标点改成空格
您可以使用 Python 中的正则表达式模块 re 来实现将文本中的标点符号替换成空格的操作。下面是一段示例代码,可以实现这个功能:
```python
import re
text = "Hello, world! This is a sentence with some punctuations."
# 将标点符号替换成空格
text = re.sub(r'[^\w\s]', ' ', text)
print(text)
```
输出结果为:
```
Hello world This is a sentence with some punctuations
```
这里的正则表达式 `[^\w\s]` 是用来匹配非单词字符和非空格字符的。`re.sub()` 函数会将匹配到的字符替换成空格。