B
B
barswert2020-05-10 23:09:07
Python
barswert, 2020-05-10 23:09:07

I can’t solve the problem, I wrote a program, but an error comes out: invalid literal for int () with base 10: ''?

The task is to write a program that reads text from a file (example: a2b3) and writes the result back to a file (example: aabbb), but something went wrong, it gives an error:
Traceback (most recent call last):
File "test.py ", line 9, in
output=s[i]*int(s[i+1]) ValueError
: invalid literal for int() with base 10: ''

import re
import os
with open(os.path.join('/','home','barswert','python lessons','dataset_3363_2.txt')) as file:
    s=file.readline().strip()
    s=re.split("(\d*)", s)[:-1]
    out=open((os.path.join('/','home','barswert','python lessons','dataset_3363_2.txt')),'w')
    for i in range(len(s)):
        if i%2==0:
            output=s[i]*int(s[i+1])
            print(output)
            out.write(output )
        else:
            continue
out.close()

I use ubuntu+sublime

Update: in addition to the error, the content is deleted when the file is written

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2020-05-12
@barswert

If I understand correctly, then this should be replaced with this: well, the cycle should be slightly changed:
s=re.split("(\d*)", s)[:-1]
s = [x for x in re.split("(\d+)", s) if x.strip()]

...
    output = ''
    for i in range(len(s)):
        if i%2==0:
            output += s[i]*int(s[i+1])
    print(output)
    out.write(output )

R
Ronald McDonald, 2020-05-10
@Zoominger

Try:
output=int(s[i])*int(s[i+1])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question