如何去除所有整数和空格的字符串

时间:2016-05-04 11:30:06

标签: python python-3.x python-3.4 python-3.3

我想知道如何去除所有整数和空格的输入。我知道Python中的.strip()函数可以做到这一点,但它只适用于字符串开头/结尾的字符。

这是我的代码:

    battery = input("Is the phone charger turned on at the plug?").lower()
        if battery == "y" or battery == "yes":
            print("Replace the phone's battery or contact the phone's manufacturer.")
            break

因此,如果用户输入'ye2s',程序将摆脱'2'并将其视为'是'。

4 个答案:

答案 0 :(得分:3)

您可以使用<?php $CI =& get_instance(); $CI->your_method($param); ?> 字符串方法执行以下操作:

isdigit()

答案 1 :(得分:2)

您可以使用translatestr.maketrans的最后一个参数是要删除的字符:

>>> table = str.maketrans("", "", "0123456789 ")
>>> "ye2s with spac3es".translate(table)
'yeswithspaces'

这可能比将字符串作为列表操作更快。

处理所有unicode十进制字符

正如J.F.Sebastian所指出的,unicode提供了很多 更多字符被视为十进制数字。

所有数字:

>>> len("".join(c for c in map(chr, range(sys.maxunicode + 1)) if c.isdecimal()))
460

所以要删除所有可能的十进制(和空格)字符:

>>> delchars = "".join(c for c in map(chr, range(sys.maxunicode + 1)) if c.isdecimal() or c.isspace())
>>> table = str.maketrans("", "", delchars)
>>> "ye2s with spac3es".translate(table)
'yeswithspaces'

答案 2 :(得分:2)

您也可以使用regular expressions来完成工作,请注意\d表示任何数字\s表示任何空格:

>>> import re
>>> input = 'ye255 s'
>>> re.sub('[\d\s]+', '', 'ye255 s')
'yes'

答案 3 :(得分:0)

所有好的答案,你选择的任何方法都没有错。 我的回答是使用.lower(),因此您的计划将识别"Y" "Yes" "YEs""YES"

更改此行:

if battery == "y" or battery == "yes":

到这一行:

if battery.lower() == "y" or battery.lower() == "yes":

或者,如果您只想使用.lower()一次,则可以执行此操作

if battery.lower() in ["y", "yes"]:

HTH。