[英]python 3 remove before and after on string
I have this string /1B5DB40?full
and I want to convert it to 1B5DB40
. 我有这个字符串
/1B5DB40?full
,我想将其转换为1B5DB40
。
I need to remove the ?full
and the front /
我需要删除
?full
和front /
My site won't always have ?full
at the end so I need something that will still work even if the ?full
is not there. 我的网站在结尾处不会总是有
?full
,因此即使没有“ ?full
,我也需要一些仍然可以工作的东西。
Thanks and hopefully this isn't too confusing to get some help :) 谢谢,希望这不会让您感到困惑:)
EDIT: 编辑:
I know I could slice at 0 and 8 or whatever, but the 1B5DB40
could be longer or shorter. 我知道我可以在0和8处进行分割,但是
1B5DB40
可以更长或更短。 For example it could be /1B5DB4000?full
or /1B5
例如,它可能是
/1B5DB4000?full
或/1B5
Using str.lstrip
(to remove leading /
) and str.split
(to remove optinal part after ?
): 使用
str.lstrip
(删除前导/
)和str.split
(删除?
之后的最佳部分):
>>> '/1B5DB40?full'.lstrip('/').split('?')[0]
'1B5DB40'
>>> '/1B5DB40'.lstrip('/').split('?')[0]
'1B5DB40'
or using urllib.parse.urlparse
: 或使用
urllib.parse.urlparse
:
>>> import urllib.parse
>>> urllib.parse.urlparse('/1B5DB40?full').path.lstrip('/')
'1B5DB40'
>>> urllib.parse.urlparse('/1B5DB40').path.lstrip('/')
'1B5DB40'
You can use lstrip
and rstrip
: 您可以使用
lstrip
和rstrip
:
>>> data.lstrip('/').rstrip('?full')
'1B5DB40'
This only works as long as you don't have the characters f
, u
, l
, ?
这只只要你没有的人物作品
f
, u
, l
, ?
, /
in the part that you want to extract. ,
/
在您要提取的部分中。
You can use regular expressions: 您可以使用正则表达式:
>>> import re
>>> extract = re.compile('/?(.*?)\?full')
>>> print extract.search('/1B5DB40?full').group(1)
1B5DB40
>>> print extract.search('/1Buuuuu?full').group(1)
1Buuuuu
What about regular expressions? 那正则表达式呢?
import re
re.search(r'/(?P<your_site>[^\?]+)', '/1B5DB40?full').group('your_site')
In this case it matches everything that is between '/'
and '?'
在这种情况下,它匹配
'/'
和'?'
之间'/'
所有内容 , but you can change it to your specific requirements ,但您可以根据自己的特定要求进行更改
>>> '/1B5DB40?full'split('/')[1].split('?')[0]
'1B5DB40'
>>> '/1B5'split('/')[1].split('?')[0]
'1B5'
>>> '/1B5DB40000?full'split('/')[1].split('?')[0]
'1B5DB40000'
Split will simply return a single element list containing the original string if the separator is not found. 如果找不到分隔符, Split将仅返回包含原始字符串的单个元素列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.