[英]How to remove substring from string in Python 3
我是Python 3的新手。目前,我正在一個項目中,需要ne檢查一個csv文件(不使用csv模塊)並提取數字。 盡管我已經能夠完成大部分提取工作,但是我的問題是每行的最后一個數字都印有"\\n,"
,這意味着我無法將其轉換為浮點數。 我如何擺脫每一行呢?
我已經嘗試使用.rsplit("\\n")
.replace("\\n", " ")
.replace("\\\\n", " ")
並已就算做完了反斜線和2的n單獨的replace語句,但它們仍留在那里。
這是我目前所擁有的:
for row in open(filename):
row = row.split(",") # elements separated by commas
for i in range(len(row) - 1): # go through each element in the row
row[i].replace("\\n", " ") # supposed to get rid of the \n at the end
row[i] = float(row[i]) # str to float conversion
lines.append(row) # add that row to list of lines
CSV范例: 13.9, 5.2, 3.4
預期結果: [13.9, 5.2, 3.4]
實際結果: [13.9, 5.2,'3.4\\n']
抱歉,如果我格式化錯誤,這是我第一次在Stack Overflow上發帖。 任何幫助表示贊賞,謝謝!
字符串在Python中是不可變的,因此您需要始終將row[i]
分配回自身的修改后的版本:
for row in open(filename):
row = row.split(",")
for i in range(len(row) - 1):
row[i] = row[i].replace("\n", "") # CHANGE HERE
row[i] = float(row[i])
lines.append(row)
注意:使用常規字符串替換時,您不需要在\\n
的轉義符之間加倍轉義。
replace
無法就地工作。 而是返回完成替換的字符串。 因此,對於修訂1,您應將聲明從以下位置更改:
row[i].replace("\\n", " ")
至:
row[i] = row[i].replace("\\n", " ")
但是,更大的問題是從.split(",")
操作獲得的列表上的迭代。
實際上,您的迭代不足1個元素,因此永遠不會觸及最后一個項目,因此也不會刪除\\n
。 讓我們做一些數學運算:
row = ['13.9', ' 5.2', ' 3.4\n']
# len(row) == 3
# len(row) - 1 == 2
# range(len(row) - 1) == [0 1], which will do 2 iterations instead of 3
因此,解決方案2是糾正for
循環,該循環應類似於:
for row in open(filename):
row = row.split(",")
for i in range(len(row)): # notice the absence of -1
row[i] = row[i].replace("\n", "")
row[i] = float(row[i])
lines.append(row)
由於CSV文件的每一行都以\\n
結尾,因此最好在拆分列並執行轉換str
使其通過map float
之前將其剝離,如下所示:
lines = []
for row in open(filename):
row = row.strip().split(",") # first remove the "\n" then split
row = list(map(float, row)) # [13.9, 5.2, 3.4]
lines.append(row)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.