iT邦幫忙

0

python如只取最後一個括弧內的字串

  • 分享至 

  • xImage

record.description會有
'NM_001001182.3 Mus musculus bromodomain adjacent to zinc finger domain, 2B (Baz2b), mRNA'
要如何取最後一個括號內的字串,因括號可能有二個以上
我用p1 = re.compile(r'([)]', re.S)
print(re.findall(p1,record.description))

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
3
一級屠豬士
iT邦大師 1 級 ‧ 2022-03-30 20:30:43
def insidelastparentheses(str):
  return str.rpartition('(')[2].partition(')')[0]

lst = ['NM_001001182.3 Mus musculus bromodomain adjacent to zinc finger domain, 2B (Baz2b), mRNA',
       'xxx(12) yyy(second)',
       'yyy(12) zzz(second) aaa(last)',
       'yyy(12) zzz(second) aaa(3) bb(4)',
       'yyy(12) zzz(second) aaa(3) bb(4) cc(5) haha',
      ]

for str in lst:
  print(insidelastparentheses(str))

執行結果:

Baz2b
second
last
4
5
chiu235 iT邦新手 5 級 ‧ 2022-03-30 20:51:38 檢舉

謝謝您的幫助

1
EN
iT邦好手 1 級 ‧ 2022-03-30 22:15:20

附上比較笨的做法:

s = 'NM_001001182.3 Mus musculus bromodomain adjacent to zinc finger domain, 2B (Baz2b), mRNA'
length = len(s)
start = 0
end = 0

for index in range(0, length):
    if s[length - 1 - index] == ')':
        end = length - 1 - index
    if s[length - 1 - index] == '(':
        start = length - 1 - index

result = s[start + 1:end]
print(result)
chiu235 iT邦新手 5 級 ‧ 2022-03-30 22:56:11 檢舉

謝謝您,很好理解

1
I code so I am
iT邦高手 1 級 ‧ 2022-03-31 07:50:01

使用 Regular Expression 解法:

import re

x = 'NM_00100(1182.3) Mus musculus (bromodomain) adjacent to zinc finger domain, 2B (Baz2b), mRNA'

p1 = re.compile(r'\(\w*\)')
list1 = re.findall(p1, x)

#last one
if len(list1) > 0:
    print(list1[-1][1:-1])
chiu235 iT邦新手 5 級 ‧ 2022-03-31 18:27:55 檢舉

謝謝您的解法

1
mackuo
iT邦研究生 2 級 ‧ 2022-03-31 09:23:56
import re
s = 'NM_001001182.3 Mus musculus bromodomain adjacent to zinc finger domain, 2B (Baz2b), mRNA'

p1 = re.findall('\(([^)]+)', s)
print(p1[-1])

https://ithelp.ithome.com.tw/upload/images/20220331/201223356Hv1EP0qz9.jpg

chiu235 iT邦新手 5 級 ‧ 2022-03-31 18:29:50 檢舉

謝謝您原來設定框框是這樣

mackuo iT邦研究生 2 級 ‧ 2022-04-01 08:28:38 檢舉

不瞞您說,我也是google來的,哈哈!!

我要發表回答

立即登入回答