Python 滤除字符串两端的*和-
时间: 2023-11-29 19:06:19 浏览: 53
可以使用字符串的 `strip()` 方法来滤除字符串两端的指定字符。例如,要滤除字符串 `s` 两端的 `*` 和 `-`,可以这样做:
```python
s = "***-hello-world-*"
s = s.strip("*-")
print(s)
```
输出结果为:
```
hello-world
```
在 `strip()` 方法中传入的参数为需要滤除的字符集合,可以使用字符串的加法和乘法操作符来构造。例如,`"*-"` 表示需要滤除的字符为 `*` 和 `-`。
相关问题
python中怎么滤除字符串左右两端的*和-
在Python中,可以使用字符串的`strip()`方法来去除字符串左右两端的指定字符。例如,假设有一个字符串`str`,左右两端都有星号和短横线,可以使用以下代码将其去除:
```
str = "***-Hello World!-***"
new_str = str.strip("*-")
print(new_str)
```
输出结果为:
```
Hello World!
```
其中,`strip("*-")`函数表示去除字符串左右两端的星号和短横线。
需要注意的是,`strip()`方法只会去除字符串左右两端的指定字符,不会去除字符串中间的指定字符。如果想要去除字符串中间的指定字符,可以使用字符串的`replace()`方法。例如:
```
str = "***-Hello-*World!---"
new_str = str.replace("*", "").replace("-", "")
print(new_str)
```
输出结果为:
```
HelloWorld!
```
其中,`replace("*", "").replace("-", "")`表示将字符串中的星号和短横线替换为空字符串,最终得到一个没有星号和短横线的新字符串。
python滤除字符串两端符号
可以使用strip()方法来滤除字符串两端的符号。例如,如果要滤除字符串s两端的空格和双引号,可以使用以下代码:
```
s = ' "hello world" '
s = s.strip(' "')
print(s) # 输出:hello world
```
strip()方法的参数指定要滤除的字符集合,如果不指定参数,则默认过滤空格。该方法返回一个新的字符串,原字符串不会被修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)