How to print two elements without being separated by space in output in python3?

50 views Asked by At

I should write a code for calculating average of some grades in a csv file. My code is going to be check by another program(and not a human.) I already have the Help file about the checking program and I should design my code to be understandable for it.

This is my code:

import csv
from statistics import mean 

def calculate_averages(input_file_name, output_file_name):
    with open("C:\\Users\\Tandis\\Desktop\\ggg.CSV", 'r') as f:
        rows = csv.reader(f)
        for row in rows:
             name = row[0]
             name = name.strip() + ","
             scores = list()
             for grade in row[1:]:
                 scores.append(int(grade))
                 average = str(mean(scores)).strip()
             print(name,average)

  
print(calculate_averages("ggg.csv" , 'jj'))

And the output is:

mandana, 7.5
hamid, 6.066666666666666
sina, 11.285714285714286
sara, 9.75
soheila, 7.833333333333333
ali, 5
sarvin, 11.375
None
Press any key to continue . . .

But the output that checking program can understand is like:

mandana,7.5
hamid,6.066666666666666
sina,11.285714285714286
sara,9.75
soheila,7.833333333333333
ali,5.0
sarvin,11.375

I don't know how to remove the space between numbers and names in output. Any Ideas?

3

There are 3 answers

0
Osama Elsherif On BEST ANSWER

You can use end=‘’ or sep=‘’ which are params in the print function.

The code will be like the following:

print(name, average, sep=‘’)
# or you can use
print(name, average, end=‘’)

But in this case the another space is exists either on name or average variables, you can delete all the snd or start spaces while processing the data if you are process them.

0
SIGHUP On

Using an f-string to format the output is the best way to manage this.

There's also a lot of unnecessary code. Let's simplify it:

Input CSV file contents:

mandana,15,0
hamid,3,4,8
sina,11,12,19
ali,5
sarvin,11.3,11.4,12

Code:

import csv
from statistics import mean

INPUT = 'scores.csv'
OUTPUT = 'scores_out.csv'

def calculate_averages(infile, outfile):
    with open(infile, newline='') as indata, open(outfile, 'w') as outdata:
        for name, *scores in csv.reader(indata):
            _mean = mean(map(float, scores))
            output = f'{name},{_mean}'
            print(output) # to stdout
            print(output, file=outdata) # to output file

calculate_averages(INPUT, OUTPUT)

Output (stdout and file):

mandana,7.5
hamid,5.0
sina,14.0
ali,5.0
sarvin,11.566666666666666
0
Argavyon On

While there's a correct answer about using the end and sep parameters of the print function, I would recommend using a single print statement per output line constructed with a formatted string literal (also known as "f-string").

for row in rows:
    name = row[0]
    # Adding the comma becomes unnecessary, as we'll add it later on the f-string
    name = name.strip()
    scores = list()
    for grade in row[1:]:
        scores.append(int(grade))
        # No need to strip a string after casting it from another type, it will have no spaces
        # No need to explicitly convert the number to string either, that'll be handled on the f-string as well
        average = mean(scores)
    # Here we use the f-string
    print(f'{name},{average}')
    # An f-string interpolates variables on a string literal: these interpolated variables are contained within "{" and "}".
    # Be noted that f-strings don't allow the "\" as part of the string literal, but you can use it or any escape sequence as a variable.

See: Python3 documentation: 2.4.3. Formatted string literals

You may also want to refer to similar questions previously asked: