[英]Trim or remove single white space char from delimited text
我遇到了一個#分隔文件的問題,但是,在散列之間,有一個空格字符表示一個空值。 稍后嘗試查詢文件時,這會導致我出現問題。 有沒有一種方法可以刪除僅存在一個空格字符的定界行中的所有實例?
這是我文件中的示例行。
40001#World Music#Mike Oldfield#Tubular Bells# 53# # #
我希望字符串是...
40001#World Music#Mike Oldfield#Tubular Bells# 53###
使用三元條件和列表推導,您可以執行以下操作:
s = "40001#World Music#Mike Oldfield#Tubular Bells# 53# # #"
s2 = "#".join([i if i != " " else "" for i in s.split("#")])
print s2
版畫
40001#World Music#Mike Oldfield#Tubular Bells# 53###
無需進口(例如RE)
使用正則表達式 。
import re
my_str = "40001#World Music#Mike Oldfield#Tubular Bells# 53# # #"
pattern = re.compile(r'(#)\s(#)\s(#)')
new_str = re.sub(pattern, r'\1\2\3', my_str)
print(new_str)
使用re.sub
函數。
re.sub(r'(?<=#) (?=#)', r'', string)
要么
re.sub(r'(?<=#)\s(?=#)', r'', string)
例:
>>> s = "40001#World Music#Mike Oldfield#Tubular Bells# 53# # #"
>>> re.sub(r'(?<=#) (?=#)', r'', s)
'40001#World Music#Mike Oldfield#Tubular Bells# 53###'
(?<=#)
正回顧后斷言匹配必須由前面#
\\s
匹配一個空格字符。 (?=#)
正向超前,斷言匹配必須后跟#
字符。 這個正則表達式似乎可以滿足您的要求,使用積極的前瞻: http : //regexr.com/3abqs
import re
str = "40001#World Music#Mike Oldfield#Tubular Bells# 53# # #"
strf = re.sub(r'#\s+(?=#)', r'#', str)
print(strf)
您可以使用類似:
orig_str="40001#World Music#Mike Oldfield#Tubular Bells# 53# # #"
splitted_str = orig_str.split("#")[:-1]
new_str = ''
for item in splitted_str:
if item.strip():
new_str+=item
new_str+="#"
print new_str
這將打印40001#World Music#Mike Oldfield#Tubular Bells# 53###
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.