This question already has answers here:
How do I parse a string to a float or int?
(32 answers)
Closed 20 days ago.
in windows: I would like this program to run on commandline. However, I am getting an error. What am I doing wrong?
# create a method that append the letter stored in variable letter, ntimes.
import sys
def appender(letter,ntimes, sentence):
print sentence+(letter*ntimes)
appender(str(sys.argv[1]),sys.argv[2], str(sys.argv[3]))
The below is the error i get from command line in windows
C:\Users\QamarAli\Documents\afaq's stuff>appender.py "F" 10 "Hello this is sent"
Traceback (most recent call last):
File "C:\Users\QamarAli\Documents\afaq's stuff\appender.py", line 8, in <modul
e>
appender(str(sys.argv[1]),sys.argv[2], str(sys.argv[3]))
File "C:\Users\QamarAli\Documents\afaq's stuff\appender.py", line 5, in append
er
print sentence+(letter*ntimes)
TypeError: can't multiply sequence by non-int of type 'str'
C:\Users\QamarAli\Documents\afaq's stuff>
The error is pretty clear:
TypeError: can't multiply sequence by non-int of type 'str'
You're trying to multiply a sequence (in this case, a string) by something that isn't a number. Convert your argument to an integer:
appender(sys.argv[1], int(sys.argv[2]), sys.argv[3])
Also, sys.argv arguments are strings by default, so there's no need to explicitly convert them again.
The values in sys.argv are all strings. Instead of trying to convert some to strings, you need to convert the other ones to whatever non-string types you need. If you want the middle one to be an integer, call int on it.
All commandline arguments are seen by Python as strings.
Change your call to
appender(sys.argv[1], int(sys.argv[2]), sys.argv[3])
Related
This question already has answers here:
How to redirect 'print' output to a file?
(15 answers)
Closed 2 years ago.
So I have this piece of code here
#inside of a repeating "while loop"
print(even,flush=True, end=inbetween) #inbetween is what's between each number. (space, new line, etc.)
even=even+2
Which prints out a sequence of even numbers in my number generator
(https://github.com/JasonDerulo1259/JasonsGenerator)
The issue I have with it is that When I do f.write to write the result It says that I am not allowed to write something with multiple arguements. What is the work-around for this?
(here's the syntax error that shows)
File "main.py", line 34, in massprint
f.write(even,flush=True, end=inbetween)
TypeError: write() takes no keyword arguments
Also, If i try put even,flush=True, end=inbetween inside of a variable, I get this syntax error no matter how I change it.
File "main.py", line 32
placeholdervar=[even,flush=True, end=inbetween]
^
SyntaxError: invalid syntax
"Just do print(even,flush=True, end=inbetween, file=f)
– Tomerikoo"
And to print to file and console. Just add another without 'file=f'
program
error
F:\aaa\1\homerun>python hometrial.py
product_name: Sunrise Simulator Alarm Clock
Traceback (most recent call last):
File "hometrial.py", line 33, in <module>
print("desc: " + desc)
TypeError: must be str, not Tag
Where you say print("desc:" + desc), you are attempting to concatenate these 2 values. As desc is a type called Tag, "desc:" is a string. Either try casting desc to a string using the str function (str(desc)), or giving them as seperate arguments as opposed to concatenating them, by changing the + to a ,.
print("Desc: ", desc)
will work just fine :)
Why can't it just implicitly convert to a string?
Python is a strongly typed language. This means , in simple terms, operations called on data must be relevant and applicable to the type. For example, trying my_num = 5 + "5" will raise a TypeError, as adding a string ("5") and integer (5) is not possible. Tag and String are different types, and therefore Python doesn't allow you to concatenate them. In something like JavaScript (a weakly typed language), adding "5" + 5 will result in 55, as it will implicitly convert 5 to a string and then concatenate them.
I am using Python 3.6. I am using Learn Python the hard way as reference.
I have a mixed list and I am trying to print the elements. The books says to use
format code "r" since we don't know what's in the list. But I am getting error with this.
Was this working in previous versions? How can I print mixed list, each element a time.
Here is my code and error:
change = [1,'pennies',2,'dimes',3,'quarters']
for i in change:
print("I got {:r}".format(i))
Error Stack trace:
Traceback (most recent call last):
File "<pyshell#52>", line 2, in <module>
print("I got {:r}".format(i))
ValueError: Unknown format code 'r' for object of type 'int'
Thanks
For str.format, the "force to repr" conversion is done with !r. not :r; it's not asserting a type for conversion, it's saying "don't use __format__ at all, use __repr__ to perform the conversion". Make it:
print("I got {!r}".format(i))
I am trying to use a python script to call an external command a number of times, each time with a different variable.
I see there are recommendations to use subprocess.call to do this, however all the documentation I have found doesn't explain how to pass this function variables (from a list for example).
I have tried a number of different formats, and I think a substitution would be the best, but it seems like the function wont accept the variable.
The code I am trying to get working is:
#!/usr/bin/python
domain_list = ["google.com", "google.ie"]
from subprocess import call
for x in domain_list:
print x
cmd_list = ['dig', '+short', '%s'] %x
call(cmd_list, shell=True)
This is failing with:
Traceback (most recent call last):
File "./dnscheck.py", line 16, in <module>
cmd_list = ['dig', '+short', '%s'] %arg
TypeError: unsupported operand type(s) for %: 'list' and 'str'
Really I want to be able to pass a bunch of different domains (defined in a list) to dig and receive the IP's of those domains.
I've just started with python so sorry if this is very basic!
You are trying to use the modulo operator on a list, I presume you wanted to do string formatting on the last item, as the percentage symbol is overloaded to do formatting with strings, but as you just want to insert the item without any formatting, you can just give it directly:
['dig', '+short', x]
If you did want to use formatting, you would need to do it on the string:
['dig', '+short', '%s' % x]
Note however, that this is pointless given you are not doing any formatting.
When I run this code:
tickers = re.findall(r'Process Name: (\w+)', s)
file = open("C:\Documents and Settings\jppavan\My Documents\My Dropbox\Python Scripts\Processes\GoodProcesses.txt","w")
file.write(tickers)
file.close()
It returns the common error:
TypeError: expected a character buffer object
Any ideas?
findall() as the name indicates returns a Python list and not a string/buffer.
You can not write a list to file handle - how should that work?
What do you expect?
file.write(str(tickers))
for the string representation of the list?
Or
file.write(', '.join(tickers))
for a comma-separated concatenation of the list items?
Anyway...write(..) requires a string or a buffer.
Apart from that: don't call your file handle 'file'.
file() is a build-in method.