Python 从字符串中修剪特定的前导和尾随字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42026036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trim specific leading and trailing characters from a string
提问by Roi Danton
I have a string that contains a path
我有一个包含路径的字符串
str = "/example/path/with/different/trailing/delimiter\"
and I want to trim the leading and trailing /
and \
. What is the best practice in Python 3?
我想修剪前导和尾随/
和\
。Python 3 中的最佳实践是什么?
Currently I'm using
目前我正在使用
trimmedPath = str.strip("/\")
# trimmedPath is "example/path/with/different/trailing/delimiter" as desired
Two questions:
两个问题:
- Is this the best trim function for trimming specific characters in Python 3?
- Are there specific path functions for such operations in Python 3 so I don't have to set the delimiters manually?
- 这是在 Python 3 中修剪特定字符的最佳修剪函数吗?
- Python 3 中是否有针对此类操作的特定路径函数,因此我不必手动设置分隔符?
采纳答案by pmuntima
I believe strip
is the pythonic way. It is usually the case when there is a builtin function.
我相信strip
是pythonic的方式。通常是有内置函数的情况。
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.
库中有一些内置路径操纵器可用os
。如果其中一个操纵器与您的用例相匹配,您可能想要使用它们。
回答by mager
Example of strip()
in action; in this case, removing a leading plus sign:
strip()
行动中的例子;在这种情况下,删除前导加号:
In [1]: phone_number = "+14158889999"
In [2]: phone_number.strip('+')
Out[2]: '14158889999'