【IT专家】如何去除所有整数和空格的字符串 |
您所在的位置:网站首页 › python字符串去掉所有空格 › 【IT专家】如何去除所有整数和空格的字符串 |
本文由我司收集整编,推荐下载,如有疑问,请与我司联系 如何去除所有整数和空格的字符串 如何去除所有整数和空格的字符串 [ 英 ]How to strip string of all integers and spaces I want to know how to strip an input of all integers and spaces. I know the .strip() function in Python can do this, but it only works for characters at the beginning/end of the string.
我想知道如何去除所有整数和空格的输入。我知道 Python 中的 .strip ()函数可以 做到这一点,但它只适用于字符串开头 / 结尾的字符。
Here is my code:
这是我的代码:
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 So if the user inputs ‘ye2s’, the program will get rid of the ‘2’ and take it as ‘yes’.
因此,如果用户输入 ’ye2s’ ,程序将摆脱 ’2’ 并将其视为 ’ 是 ’ 。
3
You could do it like follows using isdigit() string method:
您可以使用 isdigit ()字符串方法执行以下操作:
battery = ‘‘.join(c for c in battery if not c.isdigit() and not c.isspace()) 2
You can also use regular expressions to do the job, note \d means any digit \s means any space:
您也可以使用正则表达式来完成这项工作,注意 \ d 表示任何数字 \ s 表示任何空 格:
import re input = ‘ye255 s’ re.sub(‘[\d\s]+’, ‘‘, ‘ye255 s’)’yes’ 2
You may use translate. The last argument to str.maketrans are the characters to delete:
你可以使用翻译。
str.maketrans 的最后一个参数是要删除的字符:
table = str.maketrans(““, ““, “0123456789 “) “ye2s with spac3es”.translate(table)’yeswithspaces’ It is likely to be faster than manipulating the |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |