Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python从字符串右侧的另一个字符开始获取n个字符_Python_String - Fatal编程技术网

python从字符串右侧的另一个字符开始获取n个字符

python从字符串右侧的另一个字符开始获取n个字符,python,string,Python,String,我有以下字符串: st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters" 我试图从右边第一个斜杠开始得到前七个字符。 目前我是手动操作的: st[18:-32] 如何从右侧查找第一个斜杠,然后获取前七个字符?使用str.rsplit和一个简单的索引: In [19]: st.rsplit('/', 1)[-1][:7] Out[19]: 'thisisw' 无需拆分字符串,只需使用.rfind方法: 使用rfind,

我有以下字符串:

st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters"
我试图从右边第一个斜杠开始得到前七个字符。 目前我是手动操作的:

st[18:-32]
如何从右侧查找第一个斜杠,然后获取前七个字符?

使用str.rsplit和一个简单的索引:

In [19]: st.rsplit('/', 1)[-1][:7]
Out[19]: 'thisisw'

无需拆分字符串,只需使用.rfind方法:

使用rfind,r代表right,这意味着它将从右向左查看字符串

i = st.rfind('/')
st[i + 1: i + 8]
输出


要使用路径字符串,可以使用和:

使用st.split“/”。
st[st.rfind('/')+1: st.rfind('/')+8]
st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters"
start_index = st.rfind('/') + 1
end_index = start_index +7 
print st[start_index:end_index]
st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters"
last_slash_index = st.rfind('/')
print st[last_slash_index:last_slash_index+8]
i = st.rfind('/')
st[i + 1: i + 8]
st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters"
slashes = st.split('/')
print(slashes)
print(slashes[-1:][0][:7])
['..', 'dir1', 'dir2', 'dirN', 'thisiswhatiwantonlyfirstsevencharacters']
thisisw
import os
os.path.basename(os.path.normpath(st))[:7]