1

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

I get invalid syntax when using that way
@JurgenvanVossen try it again , i fix it !
0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.