【问题标题】:Why is my code producing multiple characters?为什么我的代码会产生多个字符?
【发布时间】:2017-04-25 02:21:35
【问题描述】:

当打开一个文件并连接每个字符串的第 5 个字符时,我得到了新字符串中每个字符的重复项。我该如何解决这个问题?

def fifthchar(filename):
        l=""
        fin=open(filename, "r")
        for line in fin:
            line=line.strip()
            line=str(line)
            for i in line:
                if len(line)>=5:
                    a=line[4]
                    l+=a
        fin.close()
        return l

【问题讨论】:

    标签: python file string-concatenation


    【解决方案1】:
    def fifthchar(filename):
        l=''
        lines = []
        fin=open(filename, 'r')
        all_lines = fin.read().decode("utf-8-sig").encode("utf-8")
        lines = all_lines.splitlines()
        line =''
        for line in lines:
            line=str(line)
            line=line.strip()
            print line
            if len(line)>=5:
                a=line[4]
                l+=a
        fin.close()
        return l
    if __name__ == '__main__':
        print fifthchar("read_lines.txt")
    

    如果您想从开始和最终使用中重新删除空格

    line = line.strip()

    如果您想从字符串中删除所有空格,请使用

    line = line.replace(" ","")

    此行会自动删除预期的 BOM。

    all_lines = fin.read().decode("utf-8-sig").encode("utf-8")

    for details

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      只需删除这个不必要的行并相应地缩进:

      for i in line:
      

      由于这个原因,您正在对行中的每个字符进行连接。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-19
        • 2020-07-17
        • 2016-07-23
        • 1970-01-01
        相关资源
        最近更新 更多