0

When opening a file and concatenating the 5th character from each string, I'm getting duplicates of each character in the new string. How can I fix this?

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

2 Answers2

0
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")

if you want to reamove the withe space from the beginig and the end use

line = line.strip()

if you want to remove the all whitespace from the string use

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

this line automatically removes the expected BOM.

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

for details

hope this will help.

Community
  • 1
  • 1
R.A.Munna
  • 1,699
  • 1
  • 15
  • 29
0

Just remove this unnecessary line and indent accordingly:

for i in line:

You were doing concatenation for each character in line due to this reason.

รยקคгรђשค
  • 1,919
  • 1
  • 10
  • 18