How to fix invalid literal for int() with base 16: ''? - python

I have some hex strings (splited_colors) which I want to convert them into the colors. The splited_colors is a list with length of 221228 which its first row is like splited_colors[1] = [['ab0232'],['0013aa'],['ac0102']]. Also, I have another strings like '000000'. Some of rows are converted but the others not. I checked that, all the hex strings are the same and I don't have any unusual hex string. What is this error refers to ?
RGB_colors_1 = []
for j in range (len(splited_colors)):
RGB_1 = tuple(int(splited_colors[j][0][k:k+2], 16) for k in (0, 2, 4))
RGB_colors_1.append (RGB_1)

Check out this link to see if it helps you with your question: ValueError: invalid literal for int() with base 16: ''. This exception can be called if you have an empty string or any letter after f in the alphabet.
To find what string is causing the problem, I would add something like print(j, RGB_1) in your loop. This allows you to find the index of the hex that is causing the problem.

Related

User Input Slice String

stringinput = (str(input("Enter a word to start: ")))
removeinput = (str(input("How many character's do you want to remove?")))
if (str)(removeinput) > (str)(stringinput):
print("Cannot remove more chars than there are chars, try again")
else:
removed = stringinput[-1,-removeinput,1]
print((str)(removed))
Traceback (most recent call last):
File "C:\Users\x\PycharmProjects\pythonProject\Pynative Beginner Tasks.py", line 110, in <module>
removed = stringinput[-1,-removeinput,1]
TypeError: bad operand type for unary -: 'str'
I am doing an exercise to create an input that slices a string.
I understand that removeinput needs to be converted to a string to be part of the slice but I don't know how to convert it in the else statement.
I also need it to be a string to make a comparison incase the user inputs a number greater than the amount of chars in stringinput
It looks like you might be trying to take a slice from anywhere in the string, in which case you would need to get an input for the starting index and an ending index. In the example below I wrote it to remove the number of characters from the end of the string so if you input "hello" and "2" you are left with "hel". This behavior could be modified using the tutorial I have attached below.
Here's a modified version of your code with comments to explain the changes:
stringinput = input("Enter a word to start: ")
removeinput = int(input("How many character's do you want to remove? ")) // the int() function converts the input (a string) into an integer
if removeinput > len(stringinput):
print("Cannot remove more chars than there are chars, try again")
else:
removed = stringinput[:-removeinput] // remove the last characters based on the input
print(removed)
In your code you use (str)(removeinput) and (str)(stringinput). It looks like you are trying to cast the variables as strings, but this is not necessary as both of them are already strings by default. In the modified code I converted the input into an integer using int(). This is because your input is not an integer, it is the string version of the integer. By using int(), we are comparing the integer version of the input.
To address the error that you were getting, the syntax that you are using is not correct. Strings are indexed using colons in Python, not commas. Here is a tutorial that might help you: https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3
I hope this helps!

How to convert a string to a number where number is embed in further string

hi I have a string like this
a = "'0123','0124'"
and I am trying to convert it into something like this b = (0123,0124)
and doing something like this
b = int(a.replace(',', ''))
and getting error
ValueError: invalid literal for int() with base 10:
Try:
b = tuple(int(i[1:-1]) for i in a.split(','))
print(b)
# Output
(123, 124)
Remove the quotes, split the string at comma, and use int() to convert each of them to an integer.
b = [int(x) for x in a.replace("'", "").split(',')]
Leading zeroes don't make any sense in this result. They're part of a printed representation of a number, not the numeric value itself. You can add them when displaying the numbers later.
You can do something like this:
from ast import literal_eval
output = [int(i) for i in literal_eval("'0123','0124'")]
print(output)
The error occurs because a.replace(',', '') will only replace the , in the middle with an empty string, making it "'0123''0124'", now this still has the quotes to be handled of, that's why it raised the error.
You can split the string with the comma, and replace the single quotes with empty string and pass that to int(), like this...
a = "'0123','0124'"
b = tuple([int(i.replace("'", "")) for i in a.split(",")])
print(b)

Getting invalid literal for int() with base 10. while converting str into int

I am trying to convert a string into int but facing some difficulty. how to over come this?
random_image=['12.jpg']
s1=str(random_image)[1:-1].replace(".jpg", "")
s2=int(s1)
You first need to extract the file name from the list. That's easy as its the first and only item. Then you can slice off the last 4 chars of extension and convert to an integer:
random_image = ['12.jpg']
s1=int(random_image[0][:-4])
print(s1)
Output
12
str(random_image) evaluates to the string ['12.jpg'], so you need to strip two chars off the front and back before replacing the .jpg. Why are you explicitly calling str?
s1=str(random_image)[1:-1].replace("'",'').strip(".jpg")
s2=int(s1)
You can try this

Convert string to integer in python

def handle_client_move(req):
strmove = req.decode('utf-8')
strmove = strmove[-1:]
sendmove = strmove.strip()
print(int(sendmove))
strmove = '--' + strmove
return(strmove)
I get this errror :
ValueError: invalid literal for int() with base 10: ''
cant convert strmove to integer.
To handle this specific problem, where you're trying to convert an empty string to an integer, you could do this:
int(strmove or 0)
When strmove is the empty string, which is falsey, strmove or 0 evaluates to 0 and that works fine as an argument to int(). You could also use some other number if that's more appropriate.
strmove[-1:] will give you only last symbol in your string. If it is whitespace then strmove.strip() will return empty string. Your error
ValueError: invalid literal for int() with base 10: ''
says that '' (empty string) is invalid literal for integer (which is true).
So depending on what you want, you probably need to strip() before strmove[-1:], or something else.

python 3 int() problems

nextt[0:1] = "*2"
rds = int(nextt[0:1].replace("*",""))
And there is problem, it says:ValueError: invalid literal for int() with base 10: ''
I just need to delete "*" from string and convert it to int.
You are slicing just one character:
>>> '*2foo'[0:1]
'*'
Replacing the * gives you an empty string. Perhaps you wanted to slice two characters?
>>> '*2foo'[:2]
'*2'
If you are slicing anyway, just pick the digit character without the *:
int(nextt[1])
int('*2'.replace('*', ''))
'*2'.replace('*', '') this replaces * with empty string and results in '2'
Now you cast it to int.

Categories

Resources