[英]How to get rid of special characters in python string objects
這是我的代碼
def get_current_branch():
"returns current working branch."
init()
try:
with cd(env.repo_path):
with hide('output','running','warnings'):
cmd = 'git branch'
out = run(cmd, shell=True).split('\n')
print out
for branch in out:
if '*' in branch:
temp = branch.split(' ')[1]
out = temp
return out
except Exception as msg:
print(red("\nError!!!\n\n" + str(msg)))
以上代碼的輸出結果是:
['RALP\x1b[m\r', ' SALP\x1b[m\r', '* \x1b[32mintegration\x1b[m']
實際的分支名稱是RALP,SALP和集成。 但是所有這些特殊字符都破壞了文本處理。 如何擺脫這些角色?
使用正則表達式刪除它們
import re
out = re.sub('\x1b[^m]*m', '', out)
out = re.sub('\r$', '', out)
out = re.sub('\*', '', out)
out = out.strip()
僅供參考,這些序列是ANSI轉義碼,用於在終端中為文本添加顏色。 如果您運行git branch --no-color
,那么部分將被自動刪除。
另外,將temp = branch.split(' ')[1]
更改為temp = branch.split('*')[1]
。 這將自動刪除當前分支中的*。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.