Hey guys I'm a newbie in python programming. As the title suggests char is getting printed instead of integer for the following code snippet. Thanks.
nl=[]
inp=raw_input()
if inp.isdigit():
list=inp.split()
for s in list:
nl.append(int(s))
print nl
For example if I give an input as 1 2 3 the output obtained is ['1','2','3'] but the expected output is [1,2,3]. I want to print the answer in a list form.
Try this:
nl = [int(n) for n in raw_input().split(' ') if n.isdigit()]
print nl
You have to split the input before to use str.isdigit() because '1 2 3' is not a digit.
Warning: if the numbers can be floating point numbers, you should use a regex instead of str.isdigit()
Being a novice myself, I can somewhat understand your situation.
So lets solve all the issues here:
inp will take a string from the user. Ex: "12345", "12 45" etc.
inp.isdigit() checks whether the string inp is composed of digits or not. Mind you, we are strictly speaking about digits (no other special characters).
Ex: "12345".isdigit() returns True while "12 45".isdigit() returns False.
inp.split() will return a list of words (or items) separated by a white space. Since, isdigit() and split() are contradicting each other, you are not getting a correct answer for "12 45" (or anything like this).
Hope you get my point.
Tip : Don't use list are a variable name. The code may work fine but it is not conventional.
I like the list comprehension above but here's the same thing (without the use of isdigit) using a for loop-
nl = []
inp = raw_input()
lst = inp.split(' ')
for s in lst:
nl.append(int(s))
print nl
A couple of quick points. Spaces before and after the equal sign (=) improves readability. You probably should avoid using list as a variable name since list is a built-in function. raw_input returns a string so "if inp.isdigit()" will always return false in your code.
Related
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
I am trying to write a program that would check if the letters and numbers in a string are in the right order, and the example I am using to write it is a car registration plate. Is it possible to check if the letters and numbers in a string correspond to a format of where they are in relation to each other?
For example:
The user inputs a car's registration, and the program checks if it is a standard number plate or not, and if it isn't, the program tells the user. The format's allowed would be from a standard UK registration plate (LLNN.LLL), and the strings could be up to 10 characters long.
You should have a look at regular expressions
For example number plates in my country are 3 letters and 3 numbers (ABC-123) so the regex string would be ([a-zA-Z]{3})-([0-9]{3})
You can use http://pythex.org/ to test regex patterns.
I try to give an answer but it is likely that this is not what you want:
import re
string1 = "(LLNN.LLL)"
string2 = "(abcdefgh)"
reg = re.compile(r'\([LN]{4}\.[LN]{3}')
print bool(re.match(reg, string1))
print bool(re.match(reg, string2))
This matches all the strings that consist of (, 4 times L or N, a dot and 3 times L or N.
this code takes the registration something like xjk649 and tests it, and prints when its false:
iReg = input('Registration: ')
test = ''
for i in range(0,len(iReg)-3):
if 'abcdefghijklmnopqrstuvwxyz'.find(iReg[i]) != -1:
print('succes first three charracters')
else:
test = 'WRONG'
for j in range(3,len(iReg)):
if '0123456789'.find(iReg[j]) != -1:
print('succes last three charracters')
else:
test = 'WRONG'
if test == 'WRONG':
print('false resgistration')
hope this helped
Thanks
I have this string:
abc,12345,abc,abc,abc,abc,12345,98765443,xyz,zyx,123
What can I use to add a 0 to the beginning of each number in this string? So how can I turn that string into something like:
abc,012345,abc,abc,abc,abc,012345,098765443,xyz,zyx,0123
I've tried playing around with Regex but I'm unsure how I can use that effectively to yield the result I want. I need it to match with a string of numbers rather than a positive integer, but with only numbers in the string, so not something like:
1234abc567 into 01234abc567 as it has letters in it. Each value is always separated by a comma.
Use re.sub,
re.sub(r'(^|,)(\d)', r'\g<1>0\2', s)
or
re.sub(r'(^|,)(?=\d)', r'\g<1>0', s)
or
re.sub(r'\b(\d)', r'0\1', s)
Try following
re.sub(r'(?<=\b)(\d+)(?=\b)', r'\g<1>0', str)
If the numbers are always seperated by commas in your string, you can use basic list methods to achieve the result you want.
Let's say your string is called x
y=x.split(',')
x=''
for i in y:
if i.isdigit():
i='0'+i
x=x+i+','
What this piece of code does is the following:
Splits your string into pieces depending on where you have commas and returns a list of the pieces.
Checks if the pieces are actually numbers, and if they are a 0 is added using string concatenation.
Finally your string is rebuilt by concatenating the pieces along with the commas.
I have a function using raw_input getting a sentence from user. Then my second function splits the sentence so I am only trying to update the numbers on the sentence. This is the split sentence:
['You', 'are', '42', 'this', 'year']
I am trying to update 42 to 43 do a return and print 'You are 43 this year'
I am able to pull the number by using isdigit() but I can't increase it. This is what I have so far:
def GetDigits(sentence):
for i in sentence:
if i.isindigit():
i = i +1
return sentence
Numbers in Python are immutable objects, so when you do i = i+1, you are creating a new object. This new object is not part of your original sentence object. Also, '42' is a string. You can't apply numeric add operation on it. You need to convert it to an integer first.
This is what you need -
def GetDigits(sentence):
for idx, value in enumerate(sentence):
if value.isdigit():
sentence[idx] = int(value) +1
return sentence
There is a built in method for strings that would be much better for this, format()
age = raw_input('How old are you?')
sentence = 'You are {} this year'
print(sentence.format(age))
If you need to update it you can:
print(sentence.format(int(age) + 1))
Alternatively as function utilizing a generator comprehension:
def get_digits(sentence):
return ' '.join(str(int(word) + 1) if word.isdigit() else word for word in sentence.split())
Another hacky way through regex using re module,
import re
sentence = input("Enter the sentence : \n")
def GetDigits(sentence):
L = []
for i in sentence.split():
if re.match(r'\d+$', i):
i = int(i)+1
L.append(str(i))
else:
L.append(i)
sentence = ' '.join(L)
return(sentence)
print(GetDigits(sentence))
Output:
Enter the sentence :
You are 42 this year
You are 43 this year
You're trying to add 1 to a string, as '42' isn't the same as 42.
You need to change '42' to an int first using int(v), then increase it.
def GetDigits(sentence):
for i, v in enumerate(sentence):
if v.isdigit():
sentence[i] = str(int(v) + 1)
return sentence
The key issue here is that you're trying to find a function that lets you know when it's safe/correct to convert a string to an int—but there is no such function. There are various approximations, but the simplest thing to do is just try to convert the string. This is a general principle in Python, EAFP: Easier to Ask Forgiveness than Permission. The language has been designed around the fact that the way to check whether something will work is to just do it, then handle the case where it didn't work (normally meaning an exception). Trying to fight that design is just going to make your life harder.
But that's not the only issue; there are multiple problems here.
isindigit isn't a method of strings. Maybe you meant isdigit?
isdigit doesn't give you the right answer for, say, -3—or, for that matter, integers in non-Western scripts (which may return true for isdigit but not actually be interpretable as integers by Python).
Just because i is a string representing an integer doesn't mean it's an integer; it's still a string, and i + 1 is still a TypeError. You need to call int(i) to get its value as a number.
Just reassigning to i doesn't affect sentence at all. All you're doing is making the local variable i into a name for a different value. You need to do something with that i—either build a new sentence, or modify the sentence in-place (e.g., by using enumerate to keep track of the index, so you can do sentence[index] = …).
While it isn't clear what you're doing with the results, I'll bet you actually want to get strings back, not a mix of strings and integers, so you'll probably want to convert back to str after adding 1.
So, what you want is something like this:
def GetDigits(sentence):
new_sentence = []
for i in sentence:
try:
i = str(int(i) + 1)
except ValueError:
pass
new_sentence.append(i)
return new_sentence
However, this might be a little too clever as written. If i doesn't represent an integer, int(i) will raise a ValueError, meaning i is still referring to the original string, which we add to new_sentence. Otherwise, we'll convert it to an integer, add 1, convert back to a string, and make i refer to this new string, which we add to new_sentence. If you don't understand why new_sentence.append(i) always does the right thing, you should rewrite it more explicitly.
I've got a two letter word that I'd like to attach to a double digit number. The word is an integer and the number is a string.
Say the name of the number is "number" and the name of the word is "word".
How would you make it print both of them together without spaces. When I try it right now it still has a space between them regardless of what I try.
Thanks !
'{}{}'.format(word, number)
For example,
In [19]: word='XY'
In [20]: number=123
In [21]: print('{}{}'.format(word, number))
XY123
The print function has a sep parameter that controls spacing between items:
print(number, word, sep="")
If you need a string, rather than printing, than unutbu's answer with string formatting is better, but this may get you to your desired results with fewer steps.
In python 3 the preferred way to construct strings is by using format
To print out a word and a number joined together you would use:
print("{}{}".format(word, number))