Hi!
I have a problem. How can I inport, numbers from a txt document and make a math operation with them. I have to transform the cotent of the document into a lists?
Lets say this is the content of the file:
44 36 11
66 24
92 3 8

And onother small problem, how can I convert all text letters into capital letters?

Process numeric data from a file ...

# numeric data string, for instance from a text file
s = """\
44 36 11
66 24
92 3 8"""

mylist = []
for line in s.split('\n'):
    sublist = [float(item) for item in line.split()]
    mylist.append(sublist)

print(mylist)
print('-'*50)

# now you can process the numbers in each sublist
for sublist in mylist:
    print( "%s sum = %s" % (sublist, sum(sublist)) )

"""my result -->
[[44.0, 36.0, 11.0], [66.0, 24.0], [92.0, 3.0, 8.0]]
--------------------------------------------------
[44.0, 36.0, 11.0] sum = 91.0
[66.0, 24.0] sum = 90.0
[92.0, 3.0, 8.0] sum = 103.0
"""

Converting to capital letters is easy ...

s = "I have 3 pets!"

print( s.upper() )  # I HAVE 3 PETS!

Edited 6 Years Ago by vegaseat: n/a

So, if your file eg. numbers.txt contained
44 36 11
66 24
92 3 8

you could simply use:

mylist = []
for line in open('numbers.txt'):
    sublist = [float(item) for item in line.split()]
    mylist.append(sublist)

# test it
print(mylist)

I tested it with Ironpython 2.6 and assume it will work with regular Python too.

Thank you very much.
Another stupid question, how can I sort characters from a list one in each line, like this:
list =
x
x
x
x
x

Looks like you just want to print each character in a string:

mylist = ['xxxxx']
for c in mylist[0]:
    print c
This article has been dead for over six months. Start a new discussion instead.