简体   繁体   中英

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.

The way str.translate works is different in Py 3.x - it requires mapping a dictionary of ordinals to values, so instead you use:

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 . instead you can use 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:

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

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.

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";

What I've got is only numbers (because you mentioned that you want to be left with only numbers):

66338819171248349839434347284848429085023320498320482304222

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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