Hi,
I have a list of positive digits in a file. All I want to do is to add the negative sign (-) to each digit. Is there a code for this. eg list of digits
1 correspond -1
2 correspond-2
3 correspond -3 etc

The best way to do it is to read your file and write a new file with the negated digits. Could you be more specific about the content of your file (attach your file to a post ?).

Hi,
I have a list of positive digits in a file. All I want to do is to add the negative sign (-) to each digit. Is there a code for this. eg list of digits
1 correspond -1
2 correspond-2
3 correspond -3 etc

What about trying something similar to:

for i in range(1, 10):
    print("-" + str(i))

you may replace range(1, 10) with a list (simple solution) or a generator of your choice (more sophisticated).

EDIT: I am not sure I understood your question.

Do you mean something like this??

numarray = [1,2,-3,4,5,-25]

for n in numarray:
    print "The inverse of", num, "is", num * -1
    #print("The inverse of", num, "is", num*-1)
    # use the above line if you're using python 3.x!

The output from the program is:

>>>
The inverse of 1 is -1
The inverse of 2 is -2
The inverse of -3 is 3
The inverse of 4 is -4
The inverse of 5 is -5
The inverse of -25 is 25
>>>

Cheers for now,
Jas.

Since your numeric data comes from a file you will have strings, so you might as well use concatenation ...

# the test data
data = """\
123
44
72
27"""

fname = "numdata.txt"

# write the test file
fout = open(fname, "w")
fout.write(data)
fout.close()

# read the test file
for line in open(fname):
    line = '-' + line.strip()
    print(line)

"""my result -->
-123
-44
-72
-27
"""

If you need to do calculations with the data, convert with float().

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.