从字符串中修剪特定的前导和尾随字符 [英] Trim specific leading and trailing characters from a string
本文介绍了从字符串中修剪特定的前导和尾随字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含路径的字符串
I have a string that contains a path
str = "/example/path/with/different/trailing/delimiter\"
并且我想修剪前导和尾随 /
和 \
.Python 3 中的最佳实践是什么?
and I want to trim the leading and trailing /
and \
. What is the best practice in Python 3?
目前我正在使用
trimmedPath = str.strip("/\\")
# trimmedPath is "example/path/with/different/trailing/delimiter" as desired
两个问题:
- 这是在 Python 3 中修剪特定字符的最佳修剪函数吗?
- Python 3 中是否有针对此类操作的特定路径函数,因此我不必手动设置分隔符?
推荐答案
我相信 strip
是 Pythonic 的方式.通常是有内置函数的情况.
I believe strip
is the pythonic way. It is usually the case when there is a builtin function.
os代码>
库.如果其中一个操纵器与您的用例匹配,您可能想要使用它们.
There are a few builtin path manipulators available in the os
library. You might want to use them if one of the manipulators is a match for your use case.
这篇关于从字符串中修剪特定的前导和尾随字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文