Convert str with single and double quotations into int - python

What is the best solution to convert a '"1"' or "'1'" (string) into 1 (int) using python?
int() method will return this value error message
ValueError: invalid literal for int() with base 10: "'1'"
if you try int('"1"') or int("'1'")
The solution that I used is as follow:
tmp = '"1"'
tmp = tmp.replace('"', "")
tmp
# output: 1
The flaw in this "solution" is that the inner quotation (single/double) matters.

I would use
tmp = tmp.strip("'\"")
This removes both ' and " from the start/end of tmp.

Related

Is it possible to create an error in the input class, or what is the difference between str and input?

If I try to place the following value : "' as text when by putting it in brackets as follows: a = str(""'"), it will give the following error:
SyntaxError: EOL while scanning string literal
On the other hand if I enter "' as an input it will accept it by default as a string.
How does the input class manage to convert it to string?
And is there any sequence of keys that will cause the input class to get an error when receiving a value and converts it to string?
When you want both quote marks: " and ' inside a literal string, you can either add them separately or you can use so-called triple-quotes to surround them:
a = '''""' ''' # note the trailing space
b = """ ""'""" # note the leading space
print(a)
print(b)
This may not be what you want.
Alternatively:
double = '"'
single = "'"
a = double + single
print(a)

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)

ValueError: invalid literal for int() with base 10: '"1"'

I'm attempting to create a bar chart using a csv file and I keep getting this message.
My data is almost all integers.
for item in text_list :
pieces_list = item.strip().split(',')
print(pieces_list)
Month_list.append(pieces_list[0])
Total_list.append(int(pieces_list[1]))
The string '"1"' is three separate characters: { ", 1, " }, and " is not valid in the context of evaluating an integer. This is no doubt caused by the CSV allowing quotes around a field:
"has quotes", does not have quotes, "1"
You need to strip off those double-quotes from the beginning and end of the string first (if they're there). For example:
>>> withq = '"42"'
>>> int(withq)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '"42"'
>>> int(withq.strip('"'))
42
Just keep in mind that this will strip all " characters from the start and end of a string, so """"""""42""" will still come through as 42. And replace() will replace quotes anywhere in the string. To be absolutely safe, a better option would probably be a function to do the grunt work for you:
# Get integer from a string CSV field.
# If first and last characters are both '"', convert the inner bit.
# Otherwise, convert the whole thing.
# May throw if bit being converted in not valid integer.
def csv_int(field):
if len(field) >= 2 and field[0] == '"' and field[-1] == '"':
return int(field[1:-1])
return int(field)
Looks like I get the same error when doing
print(int('"1"'))
Notice the " surrounding the digit 1.
ValueError: invalid literal for int() with base 10: '"1"'
So I suggest you use replace() on this string or something else to remove this occurrence.
print(int('"1"'.replace('"','')))
output
1

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