Start New Discussion within our Software Development Community

I am in the process of learning python, but I have a problem some one gave me last week that I wouldn't mind solving before I get to where I actually learn about it. I think python is the best choice.

I need to generate a txt file by inserting 2 columns of numbers into a string.
Input is two columns of numbers by n rows (tab delimited txt or csv or whatever is most convenient for python). Col 1 is MinMass, Col 2 is MaxMass.
Output is (for each row, RowNum):
<Result Type="PkFilter" Name="RowNum" Color="#0000ff" Show="0" MinIntensity="0" IntensityThreshold="100" AbsIntens="0" LogScale="0" MinMass="MinMass" MaxMass="MaxMass" Integrate="1" UsePercentile="0" IntensityPercentile="0.95" FindMass="0" RelMass="1"></Result>

RowNum is a whole number at least 2 digits (so padded by a zero if <10)
MinMass and MaxMass are floating points that should not be rounded.

As an added bonus, I would love to be able to vary the color code but that is not required.

My question: where should I start, or are there any good examples to use as a template? I was thinking a loop and print command would work, but I didn't know if there was some built-in module that I could more easily specify elements and output the tagged code.

strBase1="blah blah blah kjklajaskladfjlkjasdf maxMass="
strBase2="blah blah aiopweruioweruio minMass="
strBase3="blah blah iqweuiqweru890 colorCode="
strBase4="2389023489asdfjkl qwruijasdfjklha fasdfasdf"
f1=open(<input file name>)
f2=open(<output file name>,"w")
for strLine in f1:

Use the format method

#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import unicode_literals, print_function, division

template = str("""<Result Type="PkFilter" Name="{RowNum:0>2d}"
Color="{Color}" Show="0" MinIntensity="0"
IntensityThreshold="100" AbsIntens="0"
LogScale="0" MinMass="{MinMass}"
MaxMass="{MaxMass}" Integrate="1"
FindMass="0" RelMass="1"></Result>""").replace("\n", " ")

def result(RowNum, MinMass, MaxMass, Color=str("#0000ff")):
    return template.format(
        RowNum = int(RowNum),
        MinMass = repr(float(MinMass)), # repr instead of str to keep floating precision
        MaxMass = repr(float(MaxMass)),
        Color = Color,

if __name__ == "__main__":
    print(result(5, 3.14, 31.4))

Thanks for the quick response and great answer. That seems easy enough and I am pretty embarassed to have even asked, and triple apostrophes will keep the string formatted correctly.

One thing though: I don't see how the row number (RowNum in my example output) with at least 2 digit padding gets put into the strOut though?

Thanks for all the quick help. I look forward to not being stumped by such problems in the future.

This question has already been answered. Start a new discussion instead.