[英]Remove text from brackets if certain word exist inside brackets in python
[英]Remove brackets and number inside from string Python
我已經看到很多關於如何從 Python 中的字符串中刪除括號的示例,但我沒有看到任何允許我從該字符串中刪除括號和括號內的數字的示例。
例如,假設我有一個字符串,例如“abc[1]”。 如何從字符串中刪除“[1]”以僅返回“abc”?
我嘗試了以下方法:
stringTest = "abc[1]"
stringTestWithoutBrackets = str(stringTest).strip('[]')
但這僅輸出沒有最后括號的字符串
ABC[1]
我也嘗試過使用通配符選項:
stringTest = "abc[1]"
stringTestWithoutBrackets = str(stringTest).strip('[\w+\]')
但這也會輸出沒有最后一個括號的字符串
ABC[1]
您可以為此使用正則表達式,但我認為最簡單的方法是使用split
:
>>> stringTest = "abc[1][2][3]"
>>> stringTest.split('[', maxsplit=1)[0]
'abc'
您可以使用正則表達式,但您需要將其與re
模塊一起使用:
re.sub(r'\[\d+\]', '', stringTest)
如果[<number>]
部分始終位於字符串的末尾,您還可以通過以下方式剝離:
stringTest.rstrip('[0123456789]')
雖然后一個版本可能會超出[
如果前一個字符也在剝離列表中。 例如,在"abc1[5]"
, "1"
也將被刪除。
假設您的字符串具有“text[number]”格式並且您只想保留“text”,那么您可以這樣做:
stringTest = "abc[1]"
bracketBegin = stringTest.find('[')
stringTestWithoutBrackets = stringTest[:bracketBegin]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.