'Python Input string into an integer value
I'm programming a chemistry calculator that takes the element name and turns it into the value of its charge. So hydrogen is equal to 1 but I want to ask for the actual elements like hydrogen, but it's a string value so I want to turn that string value into an integer value that's already set for example in pseudo-code like this input(First Element = Hydrogen) Hydrogen = 1 and I need to instead of printing Hydrogen it prints 1 but it'll always come out as a string.
Solution 1:[1]
The simplest approach would be to use a dictionary to map the element names to the atomic numbers, and vice versa:
elements = {
"hydrogen": 1,
"helium": 2,
}
atomic_nums = {num: elem for elem, num in elements.items()}
elems = input("input elements: ").lower().split()
print(*elems, sep=" + ", end=" = ")
print(atomic_nums[sum(elements[e] for e in elems)])
input elements: hydrogen hydrogen
hydrogen + hydrogen = helium
A more OOP approach would be to create a class and implement an __add__
operation. Enum
works pretty well as a base for this:
from enum import Enum
class Element(Enum):
NoElement = 0
Hydrogen = 1
Helium = 2
def __add__(self, other):
return type(self)(self.value + other.value)
elems = [Element.__members__[e] for e in input("input elements: ").title().split()]
print(*(e.name for e in elems), sep=" + ", end=" = ")
print(sum(elems, Element.NoElement).name)
The OOP approach makes it easier to add complexity to the addition logic, if e.g. you want your class to support specific combinations and raise an exception on ones that don't make sense from a physical standpoint, or maybe return a Compound
(another class you define) in some cases instead of an Element
.
Solution 2:[2]
turning a string into an int is easy with the int()
command
a_str_that_i_want_to_be_a_int = '44'
#first way
a_str_that_i_want_to_be_a_int = int(a_str_that_i_want_to_be_a_int)
#2nd way (will not penitently change type)
int(a_str_that_i_want_to_be_a_int) + a_int
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | myrccar |