python代码如果字符串中有()?等特殊符号则删掉他们
时间: 2023-06-04 16:05:10 浏览: 65
我可以回答这个问题。您可以使用Python中的字符串操作方法,例如使用replace()方法将特殊符号替换为空字符串。示例代码如下:
```python
str = "My string (with) special (symbols)"
special_symbols = ["(", ")", "?", "!"] # 需要删除的特殊符号列表
for symbol in special_symbols:
str = str.replace(symbol, "") # 将特殊符号替换为空字符串
print(str)
```
输出结果为:"My string with special symbols"。
请注意,本AI只提供技术咨询,并不为过程中的任何个人行为负责。
相关问题
python去除字符串特殊符号
回答: 在Python中,可以使用正则表达式来去除字符串中的特殊符号。下面是几种常见的方法:
1. 使用re.sub()函数,将除了汉字和数字之外的字符替换为空字符串。例如:
```python
import re
str1 = " 212、Python用replace()函数删除制定 符号 "
str2 = re.sub('(\[^\u4e00-\u9fa5\u0030-\u0039\])', '', str1)
print(str2) # 输出:"212用函数删除制定符号"
```
这个方法使用了正则表达式来匹配除了汉字和数字之外的字符,并将其替换为空字符串。
2. 使用strip()函数去除字符串两端的空格。例如:
```python
str1 = " 212、Python用replace()函数删除制定 符号 "
print(str1.strip()) # 输出:"212、Python用replace()函数删除制定 符号"
```
这个方法只能去除字符串两端的空格,不能去除字符串中间的空格。
3. 使用replace()函数将空格替换为空字符串。例如:
```python
str1 = " 212、Python用replace()函数删除制定 符号 "
print(str1.replace(' ', '')) # 输出:"212、Python用replace()函数删除制定符号"
```
这个方法只能去除字符串中的空格,不能去除其他特殊符号。
综上所述,以上是几种常见的方法来去除字符串中的特殊符号。具体使用哪种方法取决于你的需求。
#### 引用[.reference_title]
- *1* *2* *3* [Python删除字符串中的符号](https://blog.csdn.net/O_nice/article/details/124043331)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
python怎么去除字符串两侧的特殊符号
可以使用Python中的`strip()`方法结合字符串的`punctuation`属性来实现去除字符串两侧的特殊符号。具体实现代码如下:
```python
import string
def remove_punctuation(s):
return s.strip(string.punctuation)
```
这里的`string.punctuation`是一个字符串,包含了所有的ASCII标点字符。`strip()`方法会删除字符串两端的空白字符和指定的字符,所以将`string.punctuation`作为参数传入`strip()`方法中,就可以删除字符串两端的特殊符号了。