将非整数字符串转换为整数的简便方法

时间:2016-11-02 02:30:22

标签: python

有没有简单的方法来转换字符串

# this will only try to call User#find if the @current variable is not already set
@current ||= User.find(session[:user_id])

# this will always attempt to call User#find
# if session[:user_id] is set to a deleted user's ID it will raise an error
@current = User.find(session[:user_id]) 

变成整数?

或者,这是一种严格的方法(只有我能想到的)才能找到'的索引。和' M'并做一些子串

3 个答案:

答案 0 :(得分:3)

如果您想保留面额,可以使用字典将最后一个字母映射到数千,数百万,数十亿等。

denominations = {
  'K': 1000,
  'M': 1000000,
  'B': 1000000000
}

然后,您可以检查最后一个字符是否是面额,因为它可能是可选的。

head = str1[:-1] # everything except the last character
tail = str1[-1]  # only the last character

# if the tail is one of the denominations, multiple the value
if tail in denominations:
    value = int(float(head)) * denominations[tail]
else:
    value = int(float(str1))

注意:这可以进一步优化,但我已经写了很长时间,以明确发生了什么。

答案 1 :(得分:1)

如果它们都是那种确切的格式,那么这应该有效,因为它会在最后删掉字母,将其转换为浮点数然后转换为int,这应该截断小数。

int(float(str1[:-1]))

答案 2 :(得分:1)

我很确定没有直接的方法(即单个函数调用)来获得答案。但你可以使用如下的简单代码。

valD = {"M" : 6, "B" : 9}

def getNumber(nstring):
    if nstring[-1] in valD:
        return int(float(nstring[:-1]) * 10**valD[nstring[-1]])
    else:
        return int(nstring)