第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Python中,如何拆分字符串并保留分隔符?

在Python中,如何拆分字符串并保留分隔符?

BIG陽 2019-07-04 16:18:49
在Python中,如何拆分字符串并保留分隔符?這是最簡單的解釋方法。我用的是:re.split('\W', 'foo/bar spam\neggs')-> ['foo', 'bar', 'spam', 'eggs']我想要的是:someMethod('\W', 'foo/bar spam\neggs')-> ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']原因是我想把一個字符串拆分成令牌,操作它,然后再把它放在一起。
查看完整描述

3 回答

?
米琪卡哇伊

TA貢獻1998條經(jīng)驗 獲得超6個贊

>>> re.split('(\W)', 'foo/bar spam\neggs')['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']


查看完整回答
反對 回復 2019-07-04
?
12345678_0001

TA貢獻1802條經(jīng)驗 獲得超5個贊

另一種在Python 3上運行良好的非正則表達式解決方案

# Split strings and keep separatortest_strings = ['<Hello>', 'Hi', '<Hi> <Planet>', '<', '']def split_and_keep(s, sep):
   if not s: return [''] # consistent with string.split()

   # Find replacement character that is not used in string
   # i.e. just use the highest available character plus one
   # Note: This fails if ord(max(s)) = 0x10FFFF (ValueError)
   p=chr(ord(max(s))+1) 

   return s.replace(sep, sep+p).split(p)for s in test_strings:
   print(split_and_keep(s, '<'))
   # If the unicode limit is reached it will fail explicitlyunicode_max_char 
   = chr(1114111)ridiculous_string = '<Hello>'+unicode_max_char+'<World>'print(split_and_keep(ridiculous_string, '<'))


查看完整回答
反對 回復 2019-07-04
  • 3 回答
  • 0 關(guān)注
  • 2315 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號