簡體   English   中英

python 3刪除字符串前后

[英]python 3 remove before and after on string

我有這個字符串/1B5DB40?full ,我想將其轉換為1B5DB40

我需要刪除?full和front /

我的網站在結尾處不會總是有?full ,因此即使沒有“ ?full ,我也需要一些仍然可以工作的東西。

謝謝,希望這不會讓您感到困惑:)

編輯:
我知道我可以在0和8處進行分割,但是1B5DB40可以更長或更短。 例如,它可能是/1B5DB4000?full/1B5

使用str.lstrip (刪除前導/ )和str.split (刪除?之后的最佳部分):

>>> '/1B5DB40?full'.lstrip('/').split('?')[0]
'1B5DB40'

>>> '/1B5DB40'.lstrip('/').split('?')[0]
'1B5DB40'

或使用urllib.parse.urlparse

>>> import urllib.parse
>>> urllib.parse.urlparse('/1B5DB40?full').path.lstrip('/')
'1B5DB40'
>>> urllib.parse.urlparse('/1B5DB40').path.lstrip('/')
'1B5DB40'

您可以使用lstriprstrip

>>> data.lstrip('/').rstrip('?full')
'1B5DB40'

這只只要你沒有的人物作品ful? /在您要提取的部分中。

您可以使用正則表達式:

>>> import re

>>> extract = re.compile('/?(.*?)\?full')
>>> print extract.search('/1B5DB40?full').group(1)
1B5DB40
>>> print extract.search('/1Buuuuu?full').group(1)
1Buuuuu

那正則表達式呢?

import re
re.search(r'/(?P<your_site>[^\?]+)', '/1B5DB40?full').group('your_site')

在這種情況下,它匹配'/''?'之間'/'所有內容 ,但您可以根據自己的特定要求進行更改

>>> '/1B5DB40?full'split('/')[1].split('?')[0]
'1B5DB40'
>>> '/1B5'split('/')[1].split('?')[0]
'1B5'
>>> '/1B5DB40000?full'split('/')[1].split('?')[0]
'1B5DB40000'

如果找不到分隔符, Split將僅返回包含原始字符串的單個元素列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM