python删除字符串
时间: 2023-09-02 10:14:07 浏览: 42
要删除 Python 中的字符串,你可以使用 `del` 语句或者使用字符串的 `replace()` 方法。以下是一些示例:
使用 `del` 语句删除字符串:
```python
my_string = "Hello, World!"
del my_string
```
使用 `replace()` 方法删除字符串中的指定子字符串:
```python
my_string = "Hello, World!"
new_string = my_string.replace("World", "")
print(new_string) # 输出: "Hello, !"
```
注意,`replace()` 方法并不会修改原始字符串,而是会返回一个新的字符串。如果你想要修改原始字符串,可以将其赋值为 `replace()` 方法的输出。
相关问题
python 删掉字符串空格
在 Python 中,可以使用 `strip()` 方法来删除字符串两侧的空格,使用 `lstrip()` 方法来删除字符串左侧的空格,使用 `rstrip()` 方法来删除字符串右侧的空格。
示例代码如下:
```python
str1 = " hello world "
print(str1.strip()) # 输出 "hello world"
print(str1.lstrip()) # 输出 "hello world "
print(str1.rstrip()) # 输出 " hello world"
```
如果要删除字符串中间的空格,可以使用 `replace()` 方法来替换空格为空字符串,示例代码如下:
```python
str1 = "hello world"
str2 = str1.replace(" ", "")
print(str2) # 输出 "helloworld"
```
python删掉字符串两边空白字符
在Python中,可以使用字符串的`strip()`方法来删除字符串两边的空白字符。`strip()`方法会返回一个新的字符串,该字符串是原始字符串去除两边空白字符后的结果。
以下是一个示例:
```python
string = " Hello, World! "
new_string = string.strip()
print(new_string) # 输出: "Hello, World!"
```
`strip()`方法还可以接受一个参数,用于指定要删除的字符。例如,如果想删除字符串两边的所有逗号和句点,可以这样使用:
```python
string = ",,Hello, World!.."
new_string = string.strip(",.")
print(new_string) # 输出: "Hello, World"
```