'How to remove single quotes output?
I have a code, which takes a string from input_file_1 and two numbers to slice the string from input_file_2, the output strings are written in output_file and divided by space:
def task_3(input_file_1, input_file_2, output_file):
with open(input_file_1) as i_f_1, open(input_file_2) as i_f_2, open(output_file, 'w') as o_f:
result = []
for line_1, line_2 in zip(i_f_1.readlines(), i_f_2.readlines()):
start, finish = line_2.split()
result.append(line_1[int(start):int(finish)+1])
o_f.write(' '.join(repr(i) for i in result))
task_3('test_import_file_2_1.txt', 'test_import_file_2_2.txt', 'output_file.txt')
The problem is that output looks like this:
'tPGRIXNp' 'JEflNBYRbuLkOiZqQHYNNTWPUIPNibcIpSL' 'yDvBXxyOUwjGAemSbsuHupMmGIWpTwv'...
Whereas it must look like this:
tPGRIXNp JEflNBYRbuLkOiZqQHYNNTWPUIPNibcIpSL yDvBXxyOUwjGAemSbsuHupMmGIWpTwv...
As you can see strings are attached to single quotes, which I can't get rid off.
Solution 1:[1]
You can try removing function "repr"
o_f.write(' '.join(i for i in result))
Also you can provide an example of your input files to reproduce the problem on my computer.
Solution 2:[2]
Just remove repr and you'll get what you want.
The reason: repr("string") = "'string'". So it adds a pair of single quotes to every line of your output.
Solution 3:[3]
Usually the builtin that you must use to convert a value to string in Python is str, not repr.
str and repr call the methods __str__ and __repr__ of the object. You can check in this answer how they work and that are the use cases.
Solution 4:[4]
If you want to just remove "'", you can just use
String_name.replace("'","")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Masizo Robles |
| Solution 2 | yzhang |
| Solution 3 | Francisco Puga |
| Solution 4 | Faraaz Kurawle |
