我有以下格式的字符串:替換一些前綴開頭的所有字符串
str = "1:20 2:25 3:0.432 2:-17 10:12"
我想例如更換所有字符串的開始"2:"
到"2:0"
,從而有:
str = "1:20 2:0 3:0.432 2:0 10:12"
的replace
功能是不夠的,因爲它會導致
str.replace("2:", "2:0") = "1:20 2:025 3:0.432 2:0-17 10:12"
是否有Python功能?
我有以下格式的字符串:替換一些前綴開頭的所有字符串
str = "1:20 2:25 3:0.432 2:-17 10:12"
我想例如更換所有字符串的開始"2:"
到"2:0"
,從而有:
str = "1:20 2:0 3:0.432 2:0 10:12"
的replace
功能是不夠的,因爲它會導致
str.replace("2:", "2:0") = "1:20 2:025 3:0.432 2:0-17 10:12"
是否有Python功能?
一種解決方案是使用正則表達式:
import re
new_str = re.sub('2:-?\d+', '2:', '1:20 2:25 3:0.432 2:-17 10:12')
另外,如果你的字符串格式始終保證是像你給(用空格隔開,每個項目)的例子,你可以放棄使用正則表達式和使用列表理解:
new_str = ' '.join(['2:0' if s.startswith('2:') else s for s in old.split(' ')])
您可以通過使用str.startswith
和str.split
完成你的任務:
s = "1:20 2:25 3:0.432 2:-17 10:12"
print(" ".join(["2:0" if ch.startswith("2:") else ch for ch in s.split()]
輸出:,
1:20 2:0 3:0.432 2:0 10:12
ch.startswith("2:")
檢查分割後的各子,看它是否與"2:"
開始如果是這樣,我們更換與"2:0"
其他我們只是保持原始子字符串調用str.join
重新加入字符串。
您可以使用re.sub:
import re
s = "1:20 2:25 3:0.432 2:-17 10:12"
print re.sub("2:-?\d+", "2:0", s)
請注意str
是一個關鍵字(類型),您應該避免陰影,請將您的字符串命名爲s
或string
或類似的東西。
sep = ' ' # you can change the character which separates your values here
s = "1:20 2:25 3:0.432 2:-17 10:12"
values = s.split(sep) # get the sep separated strings
new_values = []
for v in values:
if v[0] == '2':
new_values.append('2:0') # change the ones which start with 2
else:
new_values.append(v) # keep the others
result = sep.join(new_values) # rejoin the values in a string
附錄:如果你特別希望確保字符串中,你正在改變以「2:」而不是檢查它是否只能與「2」開始,因爲我已經做了,你可以使用if v[:2] == '2:'
或在其他答案中指出了startswith
。 以上代碼的較短版本是:
sep = ' '
s = '1:20 2:25 3:0.432 2:-17 10:12'
s = sep.join([v if v[:2] != '2:' else '2:0' for v in s.split(sep)])
你是對的,編輯。 –
正則表達式可能是您想要探索的模塊。在您的當前任務的情況下,像下面這樣就足夠了:
rawstr = "1:20 2:25 3:0.432 2:-17 10:12"
newstr = re.sub("2:\S+", "2:0", rawstr)
應中newstr等於 '1:20 2:0 3:0.432 2:0 10:12'。這是因爲正則表達式將'2:'之後的1個非空白字符替換爲'2:0'。我強烈建議你探索的正則表達式HOWTO它提供的這些功能優異的描述:
l = str.split(' ')
l2 = []
for s in l:
if s.startswith('2:'):
s = '2:0'
l2.append(s)
new_str = ' '.join(l2)
@PM 2Ring,感謝您的編輯 – ypx
你有沒有考慮使用正則表達式? – rlms
在附註中,如果使用'str'作爲變量名稱,則會遇到錯誤,因爲它是內置類型。 – rlms