TypeError: not all arguments converted during string formatting when trying to find even numbers
Remove [
and ]
and split the string:
def is_even_num(l):
enum = []
for n in l.replace('[','').replace(']','').split(', '):
if int(n) % 2 == 0:
enum.append(n)
return enum
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))
Output:
['2', '4', '6', '8']
Another ellegant way is to use ast
:
def is_even_num(l):
enum = []
for n in ast.literal_eval(l):
if int(n) % 2 == 0:
enum.append(n)
return enum
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))
Output:
['2', '4', '6', '8']
Also for you second part of your question as said before just use ast
:
price = "[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]"
price = ast.literal_eval(price)
print( sorted(price, key=lambda x: float(x[1]), reverse=True))
Output:
[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]
Then:
y = "[[1,2,3,4],[4,5,6,7]]"
result = [[0,0],
[0,0],
[0,0],
[0,0]]
X = ast.literal_eval(y)
#iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
Output:
[1, 4]
[2, 5]
[3, 6]
[4, 7]
How to fix 'TypeError: not all arguments converted during string formatting' in Python
digit
is a string. Just typecast it using int()
:
if not int(digit) % 2:
The reason your error is occurring is because the modulus operator is also a string formatting operator, but you haven't provided the necessary arguments to string-format '2'
This for-loop will work:
for digit in masterKeyList:
if not int(digit) % 2:
firstKeyList.append(digit)
else:
secondKeyList.append(digit)
Type error on Python: not all arguments converted during string formatting
When you use the %
operator on a string, the first string needs to have formatting placeholders that will be replaced by the values after %
. But you have no %s
in the first string.
When you're creating pathnames, you should use os.path.join()
rather than string operations.
And f-strings are easier to read than concatenation and str()
calls when combining variables with strings.
import os
for _ in range(80):
for img, label in dataset:
save_image(img, os.path.join('/media/data/abc', f'img{img_num}.png', normalize=True)
print(img_num)
img_num += 1
TypeError: not all arguments converted during string formatting (Python insert datetime into postgres)
Rectifying my previous response after reading comments from @AdrianKlaver and @JohnGordon. There comments should be taken as the correct answer, I am just modifying my response so that future readers do the right thing
cursor.execute("""INSERT INTO table01(start_time_str) VALUES(%s);""", (start_time,))
As @AdrianKlaver and @JohnGordon mentioned, just watch out for the ',' in (start_time,) to pass it as a tuple to the cursor.execute()
Not all arguments converted during string formatting. Why am I having error
You are trying to perform a modulo operation on a string:
"ineuron" % 2
The last element of l
list is ["ineuron", "datasience"]
. It passes the if statement, and then j
becomes "ineuron"
and you get an error.
Related Topics
Format Output String, Right Alignment
Multiple Python Versions on the Same MAChine
How to Bypass the Google Captcha with Selenium and Python
Reading File Using Relative Path in Python Project
Pandas: Convert Categories to Numbers
How to Make a Single Legend for Many Subplots with Matplotlib
Syntaxerror: Non-Ascii Character '\Xa3' in File When Function Returns '£'
How to Take the First N Items from a Generator or List
Binning Data in Python with Scipy/Numpy
How to Write Output in Same Place on the Console
How to Plot Implicit Equations Using Matplotlib
Type Hints: Solve Circular Dependency
Why Isn't Pycharm's Autocomplete Working for Libraries I Install
How to Allow or Deny Notification Geo-Location Microphone Camera Pop Up
How to Make a Multi-Color Line in Matplotlib
How to Save a Python Interactive Session
Evenly Distributing N Points on a Sphere
Pygame Already Installed; However, Python Terminal Says "No Module Named 'Pygame' " (Ubuntu 20.04.1)