在 python 字串中將多個空格合并為一個空格字符是可行的(此處),但是合并非空格字符呢?
>>> name = "the__answer____is___42"
>>> print("_".join(list(filter(lambda x: x != '', name.split("_")))))
the_answer_is_42
有沒有更簡單的解決方案?
uj5u.com熱心網友回復:
我的做法是:
split()將原始字串按'_'.- 按 從此串列中洗掉所有空字串
if not x==''。'_'.join()在此串列中使用。
看起來像這樣(作業代碼示例):
# original string
targetString = "the__answer____is___42"
# answer
answer = '_'.join([x for x in targetString.split('_') if not x==''])
# printing the answer
print(answer)
您可以通過將其放入函式中來使其更緊湊:
def shrink_repeated_characters(targetString,character):
return character.join([x for x in targetString.split(character) if not x==''])
在shrink_repeated_characters()上面給出的引數targetString是原始字串,并且character是您要合并的字符,例如。'_'.
uj5u.com熱心網友回復:
根據您的參考:
>> import re
>> re.sub('_ ', '_', 'the__answer____is___42')
'the_answer_is_42'
# if u have more than one non-space char
>> re.sub(r'([_ ]) ', r"\1", 'the__answer____is___42')
'the_answer_is_42'
>> re.sub(r'([_ ]) ', r"\1", 'the answer is 42')
'the answer is 42'
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448815.html
