简体   繁体   English

如何从字符串中删除特殊字符

[英]How to remove special characters from a string

I've been looking into how to create a program that removes any whitespaces/special characters from user input. 我一直在研究如何创建一个程序,从用户输入中删除任何空格/特殊字符。 I wan't to be left with just a string of numbers but I've not been able to work out quite how to do this. 我不想留下一串数字,但我还没有弄清楚如何做到这一点。 Is it possible anyone can help? 有人可以提供帮助吗?

x = (input("Enter a debit card number: "))
x.translate(None, '!.;,')
print(x)

The code I have created is possibly to basic but yeah, it also doesn't work. 我创建的代码可能是基本的,但是,它也不起作用。 Can anyone please help? 有人可以帮忙吗? :) I'm using Python3. :)我正在使用Python3。

The way str.translate works is different in Py 3.x - it requires mapping a dictionary of ordinals to values, so instead you use: str.translate工作方式在Py 3.x中有所不同 - 它需要将序数字典映射到值,因此您使用:

x = input("Enter a debit card number: ")
result = x.translate(str.maketrans({ord(ch):None for ch in '!.;,'}))

Although you're better off just removing all non digits: 虽然你最好只删除所有非数字:

import re
result = re.sub('[^0-9], x, '')

Or using builtins: 或使用内置:

result = ''.join(ch for ch in x if ch.isidigit())

It's important to note that strings are immutable and their methods return a new string - be sure to either assign back to the object or some other object to retain the result. 重要的是要注意字符串是不可变的,并且它们的方法返回一个字符串 - 确保分配回对象或其他一些对象以保留结果。

You don't need translate for this aim . 你不需要translate这个目标。 instead you can use regex : 相反,你可以使用regex

import re
x = input("Enter a debit card number: ")
x = re.sub(r'[\s!.;,]*','',x)

[\\s!.;,]* match a single character present in the list below: [\\ s!。;,] *匹配下面列表中的单个字符:

Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] \\s match any white space character [\\r\\n\\t\\f ] !.;, a single character in the list !.;, literally 量词:*在零和无限次之间,尽可能多次,根据需要返回[贪心] \\ s匹配任何空白字符[\\ r \\ n \\ t \\ f]!。;列表中的单个字符!字面意思

re.sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. re.sub(pattern,repl,string,count = 0,flags = 0)返回通过替换repl替换字符串中最左边非重叠模式而获得的字符串。

Assuming that you wanted only numbers (credit card number) 假设你只想要数字(信用卡号)

import re: # or 'from re import sub'

s = re.sub('[^0-9]+', "", my_str);

I've used this as an input: my_str = "663388191712-483498-39434347!2848484;290850 2332049832048 23042 2 2"; 我用它作为输入: my_str = "663388191712-483498-39434347!2848484;290850 2332049832048 23042 2 2";

What I've got is only numbers (because you mentioned that you want to be left with only numbers): 我得到的只是数字(因为你提到你只想留下数字):

66338819171248349839434347284848429085023320498320482304222

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM