相关疑难解决方法(0)

从Python中的字符串中删除所有非数字字符("."除外)

我有一个非常好的工作snippit代码,但我想知道是否有人有任何更好的建议如何这样做:

val = ''.join([c for c in val if c in '1234567890.'])
Run Code Online (Sandbox Code Playgroud)

你会怎么做?

python

59
推荐指数
4
解决办法
6万
查看次数

Converting an alphanumeric string into a numeric one in python

我有一个字母数字数字,作为字符串“ 4525ABT2”,我试图将其“翻译”为仅一个数字。我尝试了许多方法,既聪明又愚蠢又漫长,并四处寻找(我在这里找到了Java的解决方案,但在python中不起作用。解决方案也无法将所有字符都转换为数字)。我最近的尝试是这样的

for i in alpha:    
        alpha1 = alpha.replace("A" or "B" or "C", "2")
        alpha2 = alpha1.replace("D" or "E" or "F", "3")
        alpha3 = alpha2.replace("G" or "H" or "I", "4")
        alpha4 = alpha3.replace("J" or "K" or "L", "5")
        alpha5 = alpha4.replace("M" or "N" or "O", "6")
        alpha6 = alpha5.replace("P" or "Q" or "R" or "S", "7")
        alpha7 = alpha6.replace("T" or "U" or "V", "8")
        alpha8 = alpha7.replace("W" or "X" or "Y" or "Z", "9")

phone = str(alpha8)
return phone
Run Code Online (Sandbox Code Playgroud)

提前致谢!!

python string alphanumeric

3
推荐指数
1
解决办法
487
查看次数

Pythonic方法来删除字符串中的字符

从字符串中删除不同字符的巧妙方法是什么?例如,我有以下字符串需要转换为整数:

($12,990)
$21,434
Run Code Online (Sandbox Code Playgroud)

我使用以下代码工作正常,但有没有更笨重的方法来做同样的事情?

string = string.replace(",", "")
string = string.replace("$", "")
string = string.replace("(", "-")
string = string.replace(")", "")
int(string)
Run Code Online (Sandbox Code Playgroud)

编辑:我使用的是 Python 2.7。

python string

2
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×3

string ×2

alphanumeric ×1