User Input Slice String - python

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!

Related

ValueError while inserting into mysql: invalid literal for int() with base 10-error while iterating a list of strings [duplicate]

I got this error from my code:
ValueError: invalid literal for int() with base 10: ''.
What does it mean? Why does it occur, and how can I fix it?
The error message means that the string provided to int could not be parsed as an integer. The part at the end, after the :, shows the string that was provided.
In the case described in the question, the input was an empty string, written as ''.
Here is another example - a string that represents a floating-point value cannot be converted directly with int:
>>> int('55063.000000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'
Instead, convert to float first:
>>> int(float('55063.000000'))
55063
See:https://www.geeksforgeeks.org/python-int-function/
The following work fine in Python:
>>> int('5') # passing the string representation of an integer to `int`
5
>>> float('5.0') # passing the string representation of a float to `float`
5.0
>>> float('5') # passing the string representation of an integer to `float`
5.0
>>> int(5.0) # passing a float to `int`
5
>>> float(5) # passing an integer to `float`
5.0
However, passing the string representation of a float, or any other string that does not represent an integer (including, for example, an empty string like '') will cause a ValueError:
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> int('5.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
To convert the string representation of a floating-point number to integer, it will work to convert to a float first, then to an integer (as explained in #katyhuff's comment on the question):
>>> int(float('5.0'))
5
int cannot convert an empty string to an integer. If the input string could be empty, consider either checking for this case:
if data:
as_int = int(data)
else:
# do something else
or using exception handling:
try:
as_int = int(data)
except ValueError:
# do something else
Python will convert the number to a float. Simply calling float first then converting that to an int will work:
output = int(float(input))
This error occurs when trying to convert an empty string to an integer:
>>> int(5)
5
>>> int('5')
5
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
The reason is that you are getting an empty string or a string as an argument into int. Check if it is empty or it contains alpha characters. If it contains characters, then simply ignore that part.
Given floatInString = '5.0', that value can be converted to int like so:
floatInInt = int(float(floatInString))
You've got a problem with this line:
while file_to_read != " ":
This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.
Listen to everyone else's advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.
My simple workaround to this problem was wrap my code in an if statement, taking advantage of the fact that an empty string is not "truthy":
Given either of these two inputs:
input_string = "" # works with an empty string
input_string = "25" # or a number inside a string
You can safely handle a blank string using this check:
if input_string:
number = int(input_string)
else:
number = None # (or number = 0 if you prefer)
print(number)
I recently came across a case where none of these answers worked. I encountered CSV data where there were null bytes mixed in with the data, and those null bytes did not get stripped. So, my numeric string, after stripping, consisted of bytes like this:
\x00\x31\x00\x0d\x00
To counter this, I did:
countStr = fields[3].replace('\x00', '').strip()
count = int(countStr)
...where fields is a list of csv values resulting from splitting the line.
This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input().
Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling
So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.
your answer is throwing errors because of this line
readings = int(readings)
Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.
This seems like readings is sometimes an empty string and obviously an error crops up.
You can add an extra check to your while loop before the int(readings) command like:
while readings != 0 or readings != '':
readings = int(readings)
I am creating a program that reads a
file and if the first line of the file
is not blank, it reads the next four
lines. Calculations are performed on
those lines and then the next line is
read.
Something like this should work:
for line in infile:
next_lines = []
if line.strip():
for i in xrange(4):
try:
next_lines.append(infile.next())
except StopIteration:
break
# Do your calculation with "4 lines" here
Another answer in case all of the above solutions are not working for you.
My original error was similar to OP: ValueError: invalid literal for int() with base 10: '52,002'
I then tried the accepted answer and got this error: ValueError: could not convert string to float: '52,002' --this was when I tried the int(float(variable_name))
My solution is to convert the string to a float and leave it there. I just needed to check to see if the string was a numeric value so I can handle it correctly.
try:
float(variable_name)
except ValueError:
print("The value you entered was not a number, please enter a different number")

Python Regex validation

I am brand new to Python.
I'm trying to ensure a username contains ONLY alpha characters (only a-z). I have the below code. If I type digits only (e.g. 7777) it correctly throws the error. If I type numbers and letters mix, but I START with a number, it also rejects. But if I start with a letter (a-z) and then have numbers in the string as well, it accepts it as correct. Why?
def register():
uf = open("user.txt","r")
un = re.compile(r'[a-z]')
up = re.compile(r'[a-zA-Z0-9()$%_/.]*$')
print("Register new user:\n")
new_user = input("Please enter a username:\n-->")
if len(new_user) > 10:
print("That username is too long. Max 10 characters please.\n")
register()
#elif not un.match(new_user):
elif not re.match('[a-z]',new_user):
print("That username is invalid. Only letters allowed, no numbers or special characters.\n")
register()
else:
print(f"Thanks {new_user}")
Why don't you use isalpha()?
string = '333'
print(string.isalpha()) # False
string = 'a33'
print(string.isalpha()) # False
string = 'aWWff'
print(string.isalpha()) # True
in your code, uf, un and up are unused variables.
the only point where you validate something is the line elif not re.match('[a-z]',new_user):, and you just check if there is at least one lowercase char.
To ensure that a variable contains only letters, use: elif not re.match('^[a-zA-Z]{1,10}$',new_user):
in the regex ^[a-zA-Z]{1,10}$ you find:
^ : looks for the start of the line
[a-zA-Z] : looks for chars between a and z and between A and Z
{1,10} : ensure that the char specified before (letter) is repeated between 1 and 10 times. As LhasaDad is suggesting in the comments, you may want to increase the minimum number of characters, e.g. to 4: {4,10}. We don't know what this username is for, but 1 char seems in any case too low.
$ : search for the end of the line
Since you were looking for a RegEx, I've produced and explained one, but Guy's answer is more pythonic.
IMPORTANT:
You're not asking for this, but you may encounter an error you're not expecting: since you're calling a function inside itself, you have a recursive function. If the user provides too many times (more than 1000) the wrong username, you'll receive a RecursionError
As the re.match docs say:
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object.
That's exactly what's happening in your case: a letter in the beginning of the string will satisfy the match. Try the expression [a-z]+$ which will make sure that the match expands till the end of the string.
You can check the length on the same go: [a-z]{1,10}$.

linear search in python programming

I have wriiten a code for linear search in python language. The code is working fine for single digit numbers but its not working for double digit numbers or for numbers more than that. Here is my code.
def linear_search(x,sort_lst):
i = 0
c= 0
for i in range(len(sort_lst)):
if sort_lst[i] == x :
c= c+1
if (c > 0):
print ("item found")
else :
print ("not found")
sort_lst= input("enter an array of numbers:")
item= input("enter the number to searched :")
linear_search(item,sort_lst)
any suggestions ?
Replace
sort_lst= input("enter an array of numbers:")
with:
print 'enter an array of numbers:'
sort_lst= map(int, raw_input().strip().split(' '))
If all you want is a substring search, you can just use this
print("item found" if x in sort_lst else "not found")
If you want to get more complicated, then you need to convert your input from a string to an actual list.
(assuming space separated values)
sort_lst= input("enter an array of numbers:").split()
Then, that's actually a list of strings, not integers, but as long as you compare strings to strings, then your logic should work
Note: the print statement above will still work in both cases
This may be a case of confusion between behavior in python 2.x and python 3.x, as the behavior of the input function has changed. In python 2, input would produce a tuple (12, 34) if you entered 12, 34. However, in python 3, this same function call and input produces "12, 34". Based on the parenthesis in your prints and the problem you're having, it seems clear you're using python 3 :-)
Thus when you iterate using for i in range(len(sort_lst)):, and then looking up the element to match using sort_lst[i], you're actually looking at each character in the string "12, 34" (so "1", then "2", then ",", then " ", etc.).
To get the behavior you're after, you first need to convert the string to an actual list of numbers (and also convert the input you're matching against to a string of numbers).
Assuming you use commas to separate the numbers you enter, you can convert the list using:
sorted_int_list = []
for number_string in sort_list.split(","):
sorted_int_list = int(number_string.strip())
If you are familiar with list comprehensions, this can be shortened to:
sorted_int_list = [int(number_string.strip()) for number_string in sort_list.spit(",")]
You'll also need:
item = int(item.strip())
To convert the thing you're comparing against from string to int.
And I'm assuming you're doing this to learn some programming and not just some python, but once you've applied the above conversions you can in fact check whether item is in sorted_int_list by simply doing:
is_found = item in sorted_int_list
if is_found:
print ("Found it")
else:
print ("Didn't find it :-(")
Notes:
"12, 34".split(",") produces ["12", " 34"], as the split function on strings breaks the string up into a list of strings, breaking between elements using the string you pass into it (in this case, ","). See the docs
" 12 ".strip() trims whitespace from the ends of a string

converting a single integer number input to a list in python

I am looking for a single line command in python to convert an integer input to list.
The following is the situation.
mylist=[]
mylist=list(input('Enter the numbers: '))
The above line works perfectly if i give more than one number as input. Eg 1,2,3 . But it gives Error when i give only a single digit entry. Eg: 1 . Saying it cannot convert an integer to list.
I don't want to run a loop asking user for each input. So i want a one line command which will work for one or more digits input given by user separated by commas.
Thanking you,
-indiajoe
I think that the simplest thing that you can do is:
mylist = map(int, raw_input('Enter the numbers: ').split(','))
But it's nearly the same that using a list comprehension.
You should use raw_input and convert to int with a list comprehension:
user_input = raw_input('Enter the numbers: ')
my_list = [int(i) for i in user_input.split(',')]
From the offical documentation: raw_input reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
input eval()'s what you type. So, when you type 1,2,3, the result is a tuple; when you type 1, the result is an int. Try typing 1, instead of 1. Note that your first line (mylist=[]) is unnecessary.

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

I got this error from my code:
ValueError: invalid literal for int() with base 10: ''.
What does it mean? Why does it occur, and how can I fix it?
The error message means that the string provided to int could not be parsed as an integer. The part at the end, after the :, shows the string that was provided.
In the case described in the question, the input was an empty string, written as ''.
Here is another example - a string that represents a floating-point value cannot be converted directly with int:
>>> int('55063.000000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'
Instead, convert to float first:
>>> int(float('55063.000000'))
55063
See:https://www.geeksforgeeks.org/python-int-function/
The following work fine in Python:
>>> int('5') # passing the string representation of an integer to `int`
5
>>> float('5.0') # passing the string representation of a float to `float`
5.0
>>> float('5') # passing the string representation of an integer to `float`
5.0
>>> int(5.0) # passing a float to `int`
5
>>> float(5) # passing an integer to `float`
5.0
However, passing the string representation of a float, or any other string that does not represent an integer (including, for example, an empty string like '') will cause a ValueError:
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> int('5.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
To convert the string representation of a floating-point number to integer, it will work to convert to a float first, then to an integer (as explained in #katyhuff's comment on the question):
>>> int(float('5.0'))
5
int cannot convert an empty string to an integer. If the input string could be empty, consider either checking for this case:
if data:
as_int = int(data)
else:
# do something else
or using exception handling:
try:
as_int = int(data)
except ValueError:
# do something else
Python will convert the number to a float. Simply calling float first then converting that to an int will work:
output = int(float(input))
This error occurs when trying to convert an empty string to an integer:
>>> int(5)
5
>>> int('5')
5
>>> int('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
The reason is that you are getting an empty string or a string as an argument into int. Check if it is empty or it contains alpha characters. If it contains characters, then simply ignore that part.
Given floatInString = '5.0', that value can be converted to int like so:
floatInInt = int(float(floatInString))
You've got a problem with this line:
while file_to_read != " ":
This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.
Listen to everyone else's advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.
My simple workaround to this problem was wrap my code in an if statement, taking advantage of the fact that an empty string is not "truthy":
Given either of these two inputs:
input_string = "" # works with an empty string
input_string = "25" # or a number inside a string
You can safely handle a blank string using this check:
if input_string:
number = int(input_string)
else:
number = None # (or number = 0 if you prefer)
print(number)
I recently came across a case where none of these answers worked. I encountered CSV data where there were null bytes mixed in with the data, and those null bytes did not get stripped. So, my numeric string, after stripping, consisted of bytes like this:
\x00\x31\x00\x0d\x00
To counter this, I did:
countStr = fields[3].replace('\x00', '').strip()
count = int(countStr)
...where fields is a list of csv values resulting from splitting the line.
This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input().
Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling
So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.
your answer is throwing errors because of this line
readings = int(readings)
Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.
This seems like readings is sometimes an empty string and obviously an error crops up.
You can add an extra check to your while loop before the int(readings) command like:
while readings != 0 or readings != '':
readings = int(readings)
I am creating a program that reads a
file and if the first line of the file
is not blank, it reads the next four
lines. Calculations are performed on
those lines and then the next line is
read.
Something like this should work:
for line in infile:
next_lines = []
if line.strip():
for i in xrange(4):
try:
next_lines.append(infile.next())
except StopIteration:
break
# Do your calculation with "4 lines" here
Another answer in case all of the above solutions are not working for you.
My original error was similar to OP: ValueError: invalid literal for int() with base 10: '52,002'
I then tried the accepted answer and got this error: ValueError: could not convert string to float: '52,002' --this was when I tried the int(float(variable_name))
My solution is to convert the string to a float and leave it there. I just needed to check to see if the string was a numeric value so I can handle it correctly.
try:
float(variable_name)
except ValueError:
print("The value you entered was not a number, please enter a different number")

Categories

Resources