python字符串去掉首尾字符
浏览量:167
点赞量:0
在Python中,你可以使用字符串的`strip()`方法来去掉字符串首尾的字符。`strip()`方法会返回一个去掉首尾字符的新字符串,而不会修改原始字符串。以下是使用`strip()`方法去掉首尾字符的示例代码:
```python
string = " Hello, World! "
new_string = string.strip()
print(new_string) # 输出: "Hello, World!"
```
在上面的示例中,字符串`" Hello, World! "`包含了首尾的空格字符。通过调用`strip()`方法,我们得到了一个新字符串`"Hello, World!"`,该字符串已经去掉了首尾的空格字符。
如果你只想去掉字符串首部的字符,可以使用`lstrip()`方法;如果你只想去掉字符串尾部的字符,可以使用`rstrip()`方法。这些方法的用法与`strip()`方法相似,只是它们只会作用于字符串的一侧。
```python
string = "###Hello, World!###"
new_string = string.strip("#")
print(new_string) # 输出: "Hello, World!"
string = "###Hello, World!###"
new_string = string.lstrip("#")
print(new_string) # 输出: "Hello, World!###"
string = "###Hello, World!###"
new_string = string.rstrip("#")
print(new_string) # 输出: "###Hello, World!"
```
在上面的示例中,我们使用`strip()`、`lstrip()`和`rstrip()`方法去掉了字符串首尾的`#`字符。请注意,这些方法返回的都是新字符串,原始字符串并没有改变。
说明:本站所有资源仅供学习与参考,如有侵犯您的版权,请及时联系liuqiang@zjkytwl.com,我们将尽快处理。
贡献者:
刘强@垣通
邮箱: 16129997@qq.com
捐赠:

贡献者其它内容
-
liunx 查看文件及文件夹大小du命令 240 0
-
如何使用golang开发GUI软件 232 0