我在Python中有一個str
像下面。我想從中提取一個子字符串。如何從Python中使用分割或正則表達式的字符串獲取子字符串
table='abc_test_01'
number=table.split("_")[1]
我得到了test
。
我想要的是第一個_
之後的所有東西。
我想要的結果是test_01
我該如何做到這一點。
我在Python中有一個str
像下面。我想從中提取一個子字符串。如何從Python中使用分割或正則表達式的字符串獲取子字符串
table='abc_test_01'
number=table.split("_")[1]
我得到了test
。
我想要的是第一個_
之後的所有東西。
我想要的結果是test_01
我該如何做到這一點。
這裏是已經被很多人給出的代碼
table='abc_test_01'
number=table.split("_",1)[1]
但上面的一個,當出現不的情況下可能會失敗在字符串,那麼你會得到IndexError: list index out of range
例如。
table='abctest01'
number=table.split("_",1)[1]
上面一個將提高IndexError
,如發生不能在字符串中
所以處理這個更準確的代碼是
table.split("_",1)[-1]
因此-1不會得到任何傷害因爲出現次數已經設置爲1次。
希望它能幫助:)
你可以做到這一點,如:
import re
string = "abc_test_01"
rx = re.compile(r'[^_]*_(.+)')
match = rx.match(string).group(1)
print(match)
或隨普通字符串函數:
string = "abc_test_01"
match = '_'.join(string.split('_')[1:])
print(match)
爲了讓子(下劃線的第一次出現後,所有字符):
number = table[table.index('_')+1:]
# Output: test_01
您可以試試這個:
編輯:感謝@valtah
的評論:
table = 'abc_test_01'
#final = "_".join(table.split("_")[1:])
final = table.split("_", 1)[1]
print final
輸出:
'test_01'
另外在評論@valtah的答案是正確的:
final = table.partition("_")[2]
print final
將輸出相同結果
「_」 加入(table.split(「_」)[1:])'會產生如此多的不必要的操作: 分割,切片,連接,當你需要的就是將'maxsplit'設置爲1.所以'table.split(「_」 ,1)[1]'也適用。 – vaultah
又好的答案!我不知道我可以用'str.split()'來做到這一點。我會編輯我的答案。謝謝你的評論。 –
沒有人提到split()
函數可以具有maxsplit論點:
str.split(SEP =無,maxsplit = -1)
返回的串中的詞的列表,使用月作爲分隔符串。如果給出maxsplit,則最多分割完成(因此,該列表將最多具有最多+1個元素)。
因此,解決辦法只有:
table.split('_', 1)[1]
'table.partition( 「_」)[2]' – vaultah
或者:'table.split( '_',1)[1]'' –