ReneGe
asked on
Python 2.7 - Save to file
Hi there,
I want to output/append "print(int(argument2) + 100)" to the file name "text.txt"
Thanks for your help,
Rene
I want to output/append "print(int(argument2) + 100)" to the file name "text.txt"
import sys
args = sys.argv[1:]
if len(args) < 2:
print("ERROR: at least 2 arguments required, but got only %d" % len(args))
sys.exit(1)
argument1, argument2 = args[:2]
argument2 = int(argument2)
print("argument1 %r" % argument1)
print("") #CLRF is intended here
print(int(argument2) + 100)
Thanks for your help,
Rene
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Python has multiple ways of formatting variables to strings.
The 'old' way is using the % operator.
It is very similiar to the printf formatting of the C language.
the more 'modern' way is the format() method of string objects.
WIth the % operator you habe
example:
so if you use %r you can see, that a is a number and b is a string
more details about the % operator at https://docs.python.org/2/ library/st dtypes.htm l#string-f ormatting
more details about the format() method at https://docs.python.org/2/ library/st ring.html# format-str ing-syntax
The 'old' way is using the % operator.
It is very similiar to the printf formatting of the C language.
the more 'modern' way is the format() method of string objects.
WIth the % operator you habe
formatstring % (var1, var2, var3)
example:
a=1
b=2
print("A=%d B=%d and A+B=%d" % (a, b, a+b)) # the old % string format operatior
print("A={} B={} A+B={}".format(a, b, a+b) # the newer more flexible, more complex format method
%d is for decimal numbers
%f for floating point numbers
%s for strings
%r for a representation of a variable
a=11
b="11"
print("a=%s and b=%s" % (a, b)) # results in a=11 and b=11
print("a=%r and b=%r" % (a, b)) # results in a=11 and b='11'
so if you use %r you can see, that a is a number and b is a string
more details about the % operator at https://docs.python.org/2/
more details about the format() method at https://docs.python.org/2/
ASKER
Thank you sooo much for your explanation :)
Cheers!!!
Cheers!!!
ASKER
Can you please explain:
-the %r in: print("argument1 %r" % argument1)
-"%d\n" and % in: fout.write("%d\n" % (int(argument2) + 100))
Thanks