python从字符串

时间:2017-03-15 08:15:11

标签: python string

我有以下字符串:

st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters"

我试图从右边的第一个斜线开始获得前七个字符。 目前我手动完成:

st[18:-32]

我怎么能通过从右边查找第一个斜线然后获得前七个字符来做到这一点?

8 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

没有必要拆分字符串,只需使用.rfind()方法:

st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters"
last_slash_index = st.rfind('/')
print st[last_slash_index:last_slash_index+8]

答案 2 :(得分:2)

st[st.rfind('/')+1: st.rfind('/')+8]

答案 3 :(得分:1)

st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters"

lst = st.split("/")

output = lst[-1][0:7]
print(output)

答案 4 :(得分:1)

st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters"
start_index = st.rfind('/') + 1
end_index = start_index +7 
print st[start_index:end_index]

答案 5 :(得分:1)

使用<form id="partner" method="POST" action="https://site-B/partner"> <input type="hidden" name="pay-method" value="base64encodedvalue" /> </form> ,r代表右,这意味着它将从右到左开始查看字符串。

rfind

答案 6 :(得分:1)

st = "../dir1/dir2/dirN/thisiswhatiwantonlyfirstsevencharacters"
slashes = st.split('/')
print(slashes)
print(slashes[-1:][0][:7])

<强>输出

['..', 'dir1', 'dir2', 'dirN', 'thisiswhatiwantonlyfirstsevencharacters']
thisisw

答案 7 :(得分:1)

要使用路径字符串,您可以使用os.path.normpathos.path.basename

import os
os.path.basename(os.path.normpath(st))[:7]