This is the code I am using to detect if a string contains letters. If none are detected, it allows the program to convert the string to a float. The idea was that I could stop the program from crashing after attempting to convert a string with letters to a float.
for i in range(1, len(argument)):
if argument[i].isalpha():
return False
print("Ran option 1")
else:
return True
print("Ran option 2")
The print lines are just to help me see which part is being executed. As it turns out, neither of them are.
http://puu.sh/ivVI7/8598b82fe8.png
This is a screenshot of the output. In the first half, it detects the "aa" string and does not crash the code. However, in the second half, it fails to detect the single "a" and attempts to convert it to a float, crashing the program. If anybody could lend a hand, it would be greatly appreciated.
If it helps, the rest of the code is here: http://pastebin.com/Cx7HbM4c
You have the print lines after the return command, so they will never be executed. Move the print above the return.
You can also make your code more pythonic and more readable:
for char in argument:
return char.isalpha()
Python strings are 0-based. The test never checks the first character in the string.
for i in range(0, len(argument)):
Filing that knowledge away, the python way (for char in argument) as shown in answers from #DeepSpace and #helmbert seems cleaner.
In Python, arrays are zero-indexed. This means, you need to start iterating at 0, not at 1!
You can reproduce this easily by simply adding a print(argument[i]) into your loop body:
def func(argument):
for i in range(1, len(argument)):
print(argument[i])
func("a") # Prints nothing
func("ab") # Prints "b"
Keeping as closely as possible to your original code, simply start iterating at 0 instead of 1:
for i in range(0, len(argument):
# ...
Easier yet, you can also iterate a string directly:
for character in argument:
print(character) # Will print every single character
# ...
Ok, if you try to find out can you convert string or not, why don't you use function like this:
def convertable(value):
try:
float(value)
return True
except ValueError:
return False
if all you want is to prevent your program from crashing, exceptions are your friends:
argument = "abc"
try:
value = float(argument)
except ValueError as e:
print e, "is unacceptable"
else:
print value, "is acceptable as a float"
finally:
print "alright"
outputs:
could not convert string to float: abc is unacceptable
alright
whereas, if argument = "3.14"
it outputs:
3.14 is acceptable as a float
alright
Of course, you can put all that logic into a function, in case you need to do it many times across your program.
Have fun!
Related
I want to print a character from a string if it is an integer.
This is a simplified and specific sample code which I wrote after zeroing-in on the problem in a code I was writing for a Kata in Codewars. While the Kata is not relevant here, I can't seem to figure out how to use data type in a conditional statement (something like if type(char) == int).
string = "th3is i1s anot4her ra2ndom strin5g"
for word in string:
for char in word:
if type(char) == int:
print(char)
You never split your string into words, so the outer loop makes no sense.
You are iterating over characters, which are length 1 strings. The type of a length 1 string is never equal to int.
You can use the str.isdigit method.
Rewritten code with a single loop:
for c in string:
if c.isdigit():
print(c)
As a oneliner:
print('\n'.join(c for c in string if c.isdigit()))
I think isdigit() can work, also you can use regex.
https://www.w3schools.com/python/ref_string_isdigit.asp
You are partially on the right track with using the type keyword, however, if you type in
type(<some variable>)
into the interpreter, you will always get an output similar to the form "<class '<type'>"
where <type> is the type of your variable. You can use the practically with this code (it's an example so modify it for your purpose):
myvar = "some python string"
if type(myvar) == "<class 'str'>":
# true
print("Is a string")
now as you can imagine, this program would output
>>> Its a string
You can make this work with any type by changing the str part of the "<class 'str'>" block to the type that you are looking for (for example: "<class 'int'>" for integers).
Hope this helps!
This can be done with regular expressions, You can import re module in Python to use regular expressions :
import re
sentences = "th3is i1s anot4her ra2ndom strin5g"
num = re.findall("[0-9]", sentences)
print(num)
Basically, this code will return all numerical values in that string
Don’t worry.. Everybody who is a master programmer today was once a beginner and therefore would have had all obvious basic questions :).
You can use, str.isnumeric() boolean check. By using that you can avoid the second for loop since the second for loop doesn’t actually make sense here.
Here is the revised code-
string = "th3is i1s anot4her ra2ndom strin5g"
for char in string:
if char.isnumeric():
print(char)
Writing a program:
Input string from the user
print out whether this string is a palindrome or not
Also, I found a few other codes online but want to work with this code only.m Please let me know the error
i = str(input())
for item in i:
print(item)
if int(i[item]) == int(i[-item]):
print('yes')
else:
print('no')
Use a String slice (The i[::-1] will reverse the string):
i = input()
if i == i[::-1]:
print("Yes")
else:
print("No")
This will take the input from the user and compare it against the same input in reverse.
try this:
word="TOT"
i=word[::-1]
if i==word:
print("palandrom")
Although for item in i: loops through every character in the string, there are several problems with your code line if int(i[item]) == int(i[-item]):. First of all, item is going to be a character from your string. So if the user types "hello", then i[item] first looks for i['h']. Since 'h' is a character and not a number, this makes Python think that i is a dictionary and not a string, and thus tells Python to look for a dictionary named i and return the value where the key is h. That won't work since i is your original string, not a dictionary.
It looks like what you meant to do here is compare i[0] (the first character in the string) to i[-1] (the last character in the string), then i[1] to i[-2], and so on. But even you if looped through the position numbers, i[-item] doesn't mathematically give you what you want.
Yet another issue here is that you're checking each character one at a time and returning "yes" or "no". What you ultimately want though is to output one simple answer: whether your string is a palindrome or not.
Also, there's no need to put str() around input(), since input returns a string anyway, even if the user enters only numerals. By the way, even though you're using i as your string variable, the usual convention in programming is to use i to denote some sort of integer, such as one you're iterating through in a for loop. But that's OK for now.
As some of the other answers have shown, i[::-1] is a quick way to return the reverse of a string itself. So if you're OK with seeing the output return True if the string is a palindrome and False if it isn't, then here's an extremely simple way to do it:
i = input()
print(i == i[::-1])
If the string i is identical to itself reversed, then i == i[::-1] returns True. If not, it returns False. The print statement then prints whichever the answer is.
However, if you really do want to do it the long way, testing character by character in a loop, then here's one way to do it. You could make a function that takes in a string and does the work:
def is_palindrome(mystring):
# The "//2" here divides by 2 and ignores the remainder. So if
# there are an even number of letters, we'll test each pair. If
# It's an odd number, then we don't care about the middle character
# anyway. Compare [0] to [-1], then [1] to [-2], [2] to [-3], and so on.
for position in range(0, len(mystring)//2):
# If we've found a mismatched pair of letters, then we can
# stop looking; we know it's not a palindrome.
if mystring[position] != mystring[(-1 * position) - 1]:
print("This is NOT a palindrome")
return # This breaks you out of the entire function.
# If we've gotten this far, then the word must be a palindrome.
print("This is a palindrome")
# Here's where we run the command to input the string, and run the function
mystring = input("Enter your string: ")
is_palindrome(mystring)
In a function in Django, the user can send me a number or a string, and I want to know if I received a number or a String (Tip: The number will always be an integer between 1-6)
I want to know if it's possible to detect this and how (with an example), as the number or string I'm getting will tell me what to do next.
You can try to convert the string to a number using int(), catching the exception:
def isNum(data):
try:
int(data)
return True
except ValueError:
return False
This returns True only if the string can be converted to an integer number.
What about: if isinstance(data, int):
I'm assuming your number will still be encased in a string, ie. "1" or "4" or "6" - if that's the case, then there are several ways to do it; you could use a regex to check whether it is a number or not, or you could knock up a function that would look something like this
def isNumber(your_input_string):
return len(your_input_string) == 1 and your_input_string in "123456"
Since the number will always be between 1 and 6, it can only be a string of length 1, and it must be contained in the string '123456', since... well, those are the allowed numbers.
EDIT:
As pointed by Martijn Pieters in the comments below, that is a roundabout way of doing it; an easier solution would be just to check whether the string is between '1' or '6'.
def isNumber(your_input_string):
return len(your_input_string) == 1 and '1' <= your_input_string <= '6'
I want to make a script which will type string letters one by one
def autotype(info):
count = len(info) #Countign number of letters of the string
splitlist = list(info)
i = int(count) #getting an error on this line! it accept i=int(0) but my loop doesnt work because of this
while i>0:
sys.stdout.write(splitlist[i])
time.sleep(0.2)
i -= 1
info = str("hello world")
autotype(info)
the error is: list index out of range
how do i fix it?
The length of a list is the number of elements in a list. But, lists start at index 0, and so they will end at index length - 1. So, to fix your code as is, it should be i = count - 1. (You don't need to cast it to an int, it's already one.)
Better yet, rather than iterating using a counter in a while loop, just use a for loop. You can use the for loop to iterate over the characters in a string.
for ch in info:
sys.stdout.write(ch)
sys.stdout.flush() # as mawimawi suggests, if you don't do this, it will
# actually just come out all on one line at once.
time.sleep(0.2)
You also don't need to cast "hello world" to a string - it's already one.
Your script is quite un-pythonic. Here is something that would do the same. Strings are iterables, so:
def autotype(info):
for x in info:
sys.stdout.write(x)
sys.stdout.flush() # you need this, because otherwise its' buffered!
time.sleep(0.2)
That's all you need.
You're starting your loop at i=len(info), which is one more than the final index in the string. The last index in a string (or other iterable) is len(string) - 1, because indices begin at 0.
Note that in Python, you can (and are encouraged to) make use of the natural language constructs and the fact that collections are easy to iterate over:
for letter in reversed(info): # Much clearer way to go backwards through a string
sys.stdout.write(letter)
Since you've clarified in your comments that you actually want to go forwards through the text, you can just take out the reversed bit. The code as you posted will iterate backwards through the text, not forwards -- another benefit to using the standard iteration techniques is that it's much easier to see if you've done something you didn't mean to do!
for letter in info: # Very clear that you're going forward through the string
sys.stdout.write(letter)
Finally, as others have mentioned, you should add an explicit call to sys.stdout.flush() after every write, because otherwise there's no guarantee that you'll see output at regular intervals (it could be written to the buffer but not flushed to the screen until much later).
Lists are zero-indexed, so the last element is at len(info)-1.
To fix this, you need to subtract 1 from the count:
i = int(count) - 1
Indexes are counted from zero... if you have 5 items in a list, then indexes are 0,1,2,3,4
you are setting index out of bounds in this line:
i = int(count)
If count is 5 then max index is 4.
To fix this change that line into:
i = int(count) - 1
Next thing, you won't print the first character.
to fix that change a line:
while i>0:
into:
while i>=0:
By the way all your characters are printed backwards.
Unidiomatically, but concisely:
import time
import sys
autotype = lambda instr:map((lambda ch:(sys.stdout.write(ch), time.sleep(0.2))), instr)
autotype("hello world")
The main problem with the above code is that it's not usual to sequence two functions using tuple if you don't care for their return values.
Here is code to "make a script which will type string letters one by one"
print info
If what you need is to type letters in a string consecutively, there is no need to reinvent the wheel.
More than likely, your question was underspecified.
I am trying out this problem in a coding competition. I believe I have solved the problem, but have some problem in taking the input. Help me out here:
Input
The first line of the input contains a single integer T denoting the number of test cases. The description for T test cases follows. Each test case consists of a single line containing two space-separated strings R and S denoting the two recipes.
Now, I have coded the problem and it seems to work, but whenever I directly copy paste the input values, it fails to work by giving this error message
T= int(raw_input())
ValueError: invalid literal for int() with base 10:
'3\nalex axle\nparadise diapers\nalice bob'
Whenever I try to submit the problem, I get an error message. May be they are also copy pasting the input values and checking for the output. My code skeleton goes something like this
def whetherGranama(str1,str2):
return "NO"
#can't give the implementation out yet
T= int(raw_input())
ans=[]
for x in range(0,T):
s=raw_input()
s1,s2=s.split()
ans.append(whetherGranama(s1,s2))
for elem in ans:
print elem
How can I fix the \n error ? I think the entire input is treated as one string.
Split the input, extract the integer the process using the split list
s = raw_input()
s = s.split()
T = int(s[0])
ans=[]
for st in s[1:]:
//Do the rest
If the entire input is being read in as one string, you could try using stdin.readline() instead of raw_input to capture the input stream:
from sys import stdin
T = int(stdin.readline())
Since this is a coding competition however, I'm assuming that speed is of the essence. Since IO operations are computationally expensive, you should actually welcome the opportunity to read all of your input at one time. In other words, it's generally faster to read it in all at once and then parse the input within your code. I guess in your case, it would look something like this (assuming that it comes in all at once by design):
data = raw_input().splitlines()
#(or data = sys.stdin.read().splitlines() or data = list(sys.stdin.readlines()))
T = int(data[0])
S = (s.split() for s in data[1:])
Split your input first and then convert the int:
T, body = raw_input().split("\n", 1)
for x in xrange(int(T)):
...
That will split once and give you the first number item and then the rest of your input string.
Yes the entire string is treated as one input. You can simply store the input as a list and work with the list instead of calling raw_input in your loop, that would look something like this:
def whetherGranama(str1,str2):
return "NO"
#can't give the implementation out yet
input_lines = raw_input().split("\n")
T = int(input_lines[0])
ans=[]
for x in range(1,T):
s = input_lines[x]
s1,s2=s.split()
ans.append(whetherGranama(s1,s2))
for elem in ans:
print elem