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?

Recommended Answers

All 4 Replies

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!

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.