I have a string as an input for the code I'm writing and let an example of the string be:
"12 inches makes 1 foot"
My goal is to have my code run through this string and just pull out the integers and add them. So the output for the string above would be 13. I am using try and except in here as well since another sample input string could be something like "pi is 3.14".
msg= "12 inches makes 1 foot"
thesum = 0
s= msg.split()
for a in s:
try:
if a == int(a):
a= int(a)
thesum += a
print (thesum)
except ValueError as e:
print("Value Error: no int present")
I did what is above and I am not getting it to add the value of a (if it is an int) to "thesum". How can I get this to work? Also, I do want to have it in the try, except format so that I can call the ValueError
There is no need to check equality with a string. In fact, just try '4' == 4 in an interpreter. The answer is False because strings and integers are never equivalent. Just put thesum += int(a) into the loop instead of your if statement. If you don't want try-except, use if a.isdigit(): instead of try: and take out except: altogether:
for a in s:
if a.isdigit():
thesum += int(a)
print(thesum)
A good way would be the combination of several built-ins:
string = "12 inches makes 1 foot"
total = sum(map(int, filter(str.isdigit, string.split())))
filter() finds only the characters that are digits. We then convert each to an integer with map() and find the total with sum().
a is str, and int(a) is int(if possible), so a == int(a) will never equal.
just add the value of int(a), if the convert fails, it will raise ValueError.
The following codes should work.
msg= "12 inches makes 1 foot"
thesum = 0
s= msg.split()
for a in s:
try:
thesum += int(a)
except ValueError as e:
print a
print thesum
I like "re" and comprehension to make it easier to read:
import re
print(sum(int(a) for a in re.findall(r'\d+', '12 inches make 1 foot')))
Then you can extend the regular expression for floats, etc.
Most of the earlier approaches discount the second input which is "pi is 3.14". Although question has been asked with stated assertion of parsing integer. It requires treatment of numbers as float to successfully process second input.
import unittest
import re
def isDigit(s):
return re.match(r'[\d.]+', s)
def stringParse(input):
input = [i.strip() for i in input.split()]
input = filter(lambda x: isDigit(x), input)
input = map(lambda x: float(x), input)
return sum(input)
class TestIntegerMethods(unittest.TestCase):
def test_inches(self):
self.assertEqual(stringParse("12 inches makes 1 foot"), 13.0)
def test_pi(self):
self.assertTrue(stringParse('pi is 3.14'), 3.14)
if __name__ == '__main__':
unittest.main()
Another take on the problem
Related
If I wanted mystring = (any number between 0-9) is there any way to assign a value like this to a string?
If I had something similar to this :
mystring = "7676-[0-9]-*"
I would want this in theory to be equal to 7676-5-0 and also 7676-9-100 etc.
The reason I want this is because later in my script I will be writing a conditional statement such as:
if mystring == yourstring:
print('something cool')
else:
print('not cool')
where yourstring is equal to a number such as 7676-3-898 where it would equal mystring or 7777-7-8 where it would not equal mystring
You are looking for regex.
As an example, here is something that should be working for you:
import re
# 7676 + one digit between 0 and 9 + at least one digit between 0 and 9 (can be more)
pattern = "7676-[0-9]-[0-9]+"
and later in your code:
if re.match(pattern, "7676-9-100"):
print("something cool")
else:
print("not cool")
Alternative to regex version, you can achieve this in Pythonic way using split() function in Python:
mystring = "7676-5-*"
if '0' <= mystring.split('-')[1] <= '9':
print('something cool')
else:
print('not cool')
I'm new to Python.
I'm trying to calculate 3 ** 16 (¹[0-f], ²[0-f], ³[0-f])
but it's not working properly.
This is my code:
inp = str(input('value len 0-3 digit:'))
hexa = ('0123456789abcdef');
#len(hexa) = 16 digit
#pass = '36f'
pass = inp
for x in range(0, 3 ** len(hexa)):
#range = 0..(3 ^ 16)
if(hexa[x] == pass):
found = hexa[x]
#if result valid
print("pos: %d, pass: %s" % (x, found))
#print position
I got the error "index out of bound".
I need output like this:
000 #first
001
002
...
...
36f #found then break
...
...
fff #last
How do I fix it?
I believe your IndexError: string index out of range error comes from this logic:
for x in range(0, 3 ** len(hexa)):
Which probably should be:
for x in range(len(hexa) ** len(inp)):
A much smaller number. This is never going to work on input of more than one digit:
if(hexa[x] == pass):
You need to rethink this. Using Python's own hex() function, I came up with an approximation of what I'm guessing you're trying to do:
hexadecimal = input('hex value of 1-3 digits: ').lower()
hex_digits = '0123456789abcdef'
for x in range(len(hex_digits) ** len(hexadecimal)):
if hex(x) == "0x" + hexadecimal:
print("pos: %d, pass: %s" % (x, hexadecimal))
break
OUTPUT
> python3 test.py
hex value of 1-3 digits: 36f
pos: 879, pass: 36f
>
If that's not what you're trying to do, please explain further in your question.
Other issues to consider: don't use pass as the name of a variable, it's a Python keyword; input() returns a str, you don't need to call str on it; avoid semicolons (;) in Python.
I have a list with strings. Some of the strings contain alphabets and some contain numbers. I want to convert one of the strings with numbers in it to a float but getting an error
the list is called x. the 3rd element of the list is numbers. I tried x[2] = float (x[2]) but it gives me :Value error: could not convert string to a float:%"
See line 12 of the code where I am comparing float(x[2]) with 100
def file_read(fname):
i = 0
content_array = []
with open(fname, 'r') as f:
#Content_list is the list that contains the read lines.
for line in f:
content_array.append(line)
x = content_array[i].split('|')
i = i + 1
x[2] = x[2].strip() # to delete any empty spaces
if float(x[2]) > 50.00:
print ('got one')
print x[2]
print i
file_read('flow.txt')
Around your if statement you can wrap a try/except block, the program will try to convert float(x[2]) to a float, but if it cannot (since its a string) it will execute the except portion of the code.
try:
if float(x[2]) > 50.0:
print('got one')
except:
# do something else, if x[2] is not a float
pass # if you don't want to do anything.
You can use regular expressions to check if it's a number, and then you can safely cast it to float.
import re
rgx = "^\d*\.?\d*$"
if re.match(rgx, x):
print("it's a number!")
x = float(x)
I wanna ask how to convert an integer into string without using in-built function.
This is the original question:
Write a function string(ls) that returns a string representation of the list ls.
Note: do not use the built-in str() method for this task. We are attempting to emulate its behavior.
s = string(['a','b','c']) # '['a','b','c']'
s = string([1,2,3]) # '[1, 2, 3]'
s = string([True]) # '[True]'
s = string([]) # '[]'
Restrictions: Don't just return str(ls)! Don't use the str.join method, don't use slicing.
Here is my code:
def string(ls):
if len(ls)==0:
mess="'[]'"
return mess
elif isinstance(ls[0],str):
i=0
mess="'["
while True:
if i==len(ls)-1:
elem="'"+ls[i]+"'"
mess=mess+elem
break
else:
elem="'"+ls[i]+"', "
mess=mess+elem
i=i+1
mess=mess+"]'"
return mess
else:
i=0
mess="'["
while True:
if i==len(ls)-1:
elem=str(ls[i])+"]'"
mess=mess+elem
break
else:
elem=str(ls[i])+', '
mess=mess+elem
i=i+1
return mess
You can keep dividing a given integer by 10 and prepending the remainder to the output string. Use the ordinal number of '0' plus the remainder to obtain the ordinal number of the remainder, and then convert it to string using the chr function:
def int_to_string(i):
string = ''
while True:
i, remainder = divmod(i, 10)
string = chr(ord('0') + remainder) + string
if i == 0:
break
return string
so that:
print(int_to_string(0))
print(int_to_string(5))
print(int_to_string(65))
print(int_to_string(923))
would output:
0
5
65
923
This should work? I am fairly new so i do not know why your codes are so complicated.This should work too.
def int_to_string(i):
string = chr(ord("0") + i)
return string
My question can be understood below:
goodvalue=False
while (goodvalue==False):
try:
word=str(input("Please enter a word: "))
except ValueError:
print ("Wrong Input...")
else:
goodvalue=True
word=word.lower()
List=list(map(str,word))
lenList=len(list(map(str,word)))
listofans=[]
x=0
while (lenList-1==x):
if List[x]==str("a"):
listofans[x]=str("1")
x=x+1
elif List[x]==str("b"):
listofans[x]=str("2")
x=x+1
elif List[x]==str("c"):
listofans[x]=str("3")
x=x+1
It continues like that for all alphabets for a while... And then:
sumofnums=listofans[0]
y=1
while (lenList-2==y):
sumofnums+=listofans[y]
print ("The number is: ", sumofnums)
So basically, if I give hello, it should return 8 5 12 12 15. Any help is truly appreciated!
Your code is very messy, and some of it isn't even needed (all those uses of map is not needed. Nor is the try/except structure)
Why not simplify it a bit ;).
>>> import string
>>> d = {j:i for i, j in enumerate(string.lowercase, 1)}
>>> for i in 'hello':
... print d[i],
...
8 5 12 12 15
Some problems with your code:
Don't compare booleans like that. Just do while goodvalue.
List=list(map(str,word)) is excessive. A simple List = list(word) is needed, but you probably won't even need this as you can iterate through strings (as I have shown above)
str("a") is pointless. "a" is already a string, thus str() does nothing here.
As I said before, the try/except is not needed. No input could cause a ValueError. (unless you meant int())
Are looking for something like this?
[ord(letter)-ord('a')+1 for letter in word]
For "hello" this outputs:
[8, 5, 12, 12, 15]
The ord function returns the ascii ordinal value for the letter. Subtracting ord('a') rebases that to 0, but you have 'a' mapping to 1, so it has to be adjusted by 1.
Try this:
goodvalue=False
while (goodvalue==False):
try:
word=str(input("Please enter a word: "))
except ValueError:
print ("Wrong Input...")
else:
goodvalue=True
word=word.lower()
wordtofans=[]
for c in word:
if c >= 'a' and c <= 'z':
wordtofans.append( int(ord(c)-ord('a')+1) )
print wordtofans
You can directly iterate a string in a for loop, you don't have to convert your string to a list.
You have a control check here to ensure that only letters a..z and A..Z are converted into numbers.
Conversion from a string letter to a number is done using int(ord(c)-ord('a')+1) which uses ord function that will return a ASCII value for a supplied character.
First of all just for make your code smaller you have to look on a small stuff like, instead of print =="a" you print ==str("a"). That's wrong.
So here is your old while loop:
while (lenList-1==x):
if List[x]==str("a"):
listofans[x]=str("1")
x=x+1
elif List[x]==str("b"):
listofans[x]=str("2")
x=x+1
elif List[x]==str("c"):
listofans[x]=str("3")
x=x+1
And here is new:
while (lenList-1==x):
if List[x]=="a":
listofans[x]="1"
x=x+1
elif List[x]=="b":
listofans[x]="2"
x=x+1
elif List[x]=="c":
listofans[x]="3"
x=x+1
And about your question, here is a solution:
[ord(string)-ord('a')+1 for string in word]
If you print "hello" this will returns you:
[8, 5, 12, 12, 15]