简体   繁体   English

在python中只检索字符串的一部分

[英]Retrieve only a part of a string in python

I have a path string something like '/foo/bar1/bar2/test.txt' . 我有一个类似'/foo/bar1/bar2/test.txt'的路径字符串。 I want to retrieve just '/foo/bar1/' from the string and want to ignore the rest. 我想从字符串中检索'/foo/bar1/'并想忽略其余部分。 I tried doing that with \\/([\\w\\s]+)\\/|,(?!\\w)+? 我尝试用\\/([\\w\\s]+)\\/|,(?!\\w)+? but that didn't help. 但这没有帮助。

Can someone help me with this ? 有人可以帮我弄这个吗 ?

Thanks in advance 提前致谢

s = '/foo/bar1/bar2/test.txt'

'/'.join(s.split('/')[:3])

# returns '/foo/bar1'

Change that 3 to the appropriate number. 3更改为适当的数字。 For further path manipulation have a look at os.path methods. 有关进一步的路径操作,请查看os.path方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM