Skip to main content
 首页 » 编程设计

python之在 Python 中将 .join 函数与列表一起使用时,如何防止第一个字符成为我要加入的变量

2025年05月04日21zengkefu

def convert_table(filename_in, filename_out): 
  retlist = [] 
  with open(filename_in, 'r') as fd: 
    for line in fd: 
      split = line.split(";") 
      for i in split: 
        i = i.replace(",",";") 
        retlist.append(i) 
    s = "," 
    s = s.join(retlist) 
    print(s) 
    with open(filename_out,'w') as fdnew: 
      fdnew.write(s) 
  return True 

所以当我将此输出写入另一个文件时,所有新行都将以“,”开头,这样输出的两行是

,String,Categorical,Categorical,Int,Int,Int,Int,Float,Float,Int,Int,Int,Int,Float,Float,Float 
,100% Bran,N,C,70,4,1,130,10,5,6,280,25,3,1,0.33,68.402973 

如何去掉 String 和 100% 之前的逗号?

请您参考如下方法:

您正在从文件中读取数据,并将所有 数据放入一个 巨大的平面列表中。您读取的数据包括换行符,因此如果文件看起来像

1;2;3 
a;b;c 

然后你构建的列表看起来像

['1', '2', '3\n', 'a', 'b', 'c\n'] 

和 s.join(retlist) 结果为 '1,2,3\n,a,b,c\n',行后有一个逗号休息。


不是构建一个巨大的列表,而是每行构建一个列表并一次写一行将是解决问题的一种方法。

此外,您似乎想将所有分号都变成逗号,反之亦然。有比拆分/替换/合并更简单的方法。字符串有一个 translate 方法来用其他字符替换字符:

converted = s.translate(str.maketrans({',': ';', ';': ','}))