Python remove numbers in string

Remove characters except digits from string using Python?

\D matches any non-digit character so, the code above, is essentially replacing every non-digit character for the empty string.

Or you can use filter , like so (in Python 2):

>>> filter(str.isdigit, 'aas30dsa20') '3020' 

Since in Python 3, filter returns an iterator instead of a list , you can use the following instead:

>>> ''.join(filter(str.isdigit, 'aas30dsa20')) '3020' 

@f0b0s-iu9-info: did you timed it? on my machine (py3k) re is twice as fast than filter with isdigit , generator with isdigt is halfway between them

For Python 3.6 it should be re.sub(«\\D», «», «aas30dsa20») . Otherwise one gets a DeprecationWarning: invalid escape sequence \D .

In Python 2.*, by far the fastest approach is the .translate method:

>>> x='aaa12333bb445bb54b5b52' >>> import string >>> all=string.maketrans('','') >>> nodigs=all.translate(all, string.digits) >>> x.translate(all, nodigs) '1233344554552' >>> 

string.maketrans makes a translation table (a string of length 256) which in this case is the same as ».join(chr(x) for x in range(256)) (just faster to make;-). .translate applies the translation table (which here is irrelevant since all essentially means identity) AND deletes characters present in the second argument — the key part.

Читайте также:  Php cli error log

.translate works very differently on Unicode strings (and strings in Python 3 — I do wish questions specified which major-release of Python is of interest!) — not quite this simple, not quite this fast, though still quite usable.

Back to 2.*, the performance difference is impressive.

$ python -mtimeit -s'import string; all=string.maketrans("", ""); nodig=all.translate(all, string.digits); x="aaa12333bb445bb54b5b52"' 'x.translate(all, nodig)' 1000000 loops, best of 3: 1.04 usec per loop $ python -mtimeit -s'import re; x="aaa12333bb445bb54b5b52"' 're.sub(r"\D", "", x)' 100000 loops, best of 3: 7.9 usec per loop 

Speeding things up by 7-8 times is hardly peanuts, so the translate method is well worth knowing and using. The other popular non-RE approach.

$ python -mtimeit -s'x="aaa12333bb445bb54b5b52"' '"".join(i for i in x if i.isdigit())' 100000 loops, best of 3: 11.5 usec per loop 

is 50% slower than RE, so the .translate approach beats it by over an order of magnitude.

In Python 3, or for Unicode, you need to pass .translate a mapping (with ordinals, not characters directly, as keys) that returns None for what you want to delete. Here’s a convenient way to express this for deletion of «everything but» a few characters:

import string class Del: def __init__(self, keep=string.digits): self.comp = dict((ord(c),c) for c in keep) def __getitem__(self, k): return self.comp.get(k) DD = Del() x='aaa12333bb445bb54b5b52' x.translate(DD) 

also emits ‘1233344554552’ . However, putting this in xx.py we have.

$ python3.1 -mtimeit -s'import re; x="aaa12333bb445bb54b5b52"' 're.sub(r"\D", "", x)' 100000 loops, best of 3: 8.43 usec per loop $ python3.1 -mtimeit -s'import xx; x="aaa12333bb445bb54b5b52"' 'x.translate(xx.DD)' 10000 loops, best of 3: 24.3 usec per loop 

. which shows the performance advantage disappears, for this kind of «deletion» tasks, and becomes a performance decrease.

Источник

Remove numbers from string in Python

In this article, we will learn to delete numerical values from a given string in Python. We will use some built-in functions and some custom codes as well. Let’s first have a quick look over what is a string in Python.

Python String

The string is a type in python language just like integer, float, boolean, etc. Data surrounded by single quotes or double quotes are said to be a string. A string is also known as a sequence of characters.

string1 = "apple" string2 = "Preeti125" string3 = "12345" string4 = "pre@12"

A string in Python can contain numbers, characters, special characters, spaces, commas, etc. We will learn four different ways to remove numbers from a string and will print a new modified string.

Example: Remove Numbers from String using regex

Python provides a regex module that has a built-in function sub() to remove numbers from the string. This method replaces all the occurrences of the given pattern in the string with a replacement string. If the pattern is not found in the string, then it returns the same string.

In the below example, we take a pattern as r’9’ and an empty string as a replacement string. This pattern matches with all the numbers in the given string and the sub() function replaces all the matched digits with an empty string. It then deletes all the matched numbers.

#regex module import re #original string string1 = "Hello!James12,India2020" pattern = r'1' # Match all digits in the string and replace them with an empty string new_string = re.sub(pattern, '', string1) print(new_string)

Example: Remove Numbers from String using join() & isdigit()

This method uses isdigit() to check whether the element is a digit or not. It returns True if the element is a digit. This method uses for loop to iterate over each character in the string.

The below example skips all numbers from the string while iterating and joins all remaining characters to print a new string.

string1 = "Hello!James12,India2020" #iterating over each element new_string = ''.join((x for x in string1 if not x.isdigit())) print(new_string)

Example: Remove Numbers from String using translate()

This method uses string Python library. With the help of a string object, maketrans() separates numbers from the given string. Afterward, a translation table is created where each digit character i.e. ‘0’ to ‘9’ will be mapped to None and this translation table is passed to translate() function.

The below example creates a translation table and replaces characters in string based on this table, so it will delete all numbers from the string

import string string1 = "Hello!James12,India2020" #digits are mapped to None translation_table = str.maketrans('', '', string.digits) #deletes all number new_string = string1.translate(translation_table) print(new_string)

Example: Remove Numbers from String

This example uses the filter() and lambda in the generating expression. It filters or deletes all the numbers from the given string and joins the remaining characters of the string to create a new string.

The filter() function uses the original string and lambda expression as its arguments. First, we filtered all digit characters from a string and then joined all the remaining characters.

#original string string1 = "Hello!James12,India2020" #Filters all digits new_string = ''.join(filter(lambda x: not x.isdigit(), string1)) print(new_string)

Conclusion

In this article, we learned to remove numerical values from the given string of characters. We used different built-in functions such as join() , isdigit() , filter() , lambda , sub() of regex module. We used custom codes as well to understand the topic.

Источник

Remove Number From String Python

In Python, string includes numeric values, characters, spaces, delimiters, and many more. More specifically, while data cleaning, users want to separate multi values from the strings or remove them from the string. Multiple built-in methods or operators of Python can be used to perform this particular operation.

This write-up explained different ways to remove the numeric value from the string in Python.

How to Remove Numbers From String in Python?

To eliminate the numbers from any string in Python, the below-listed methods are utilized:

Method 1: Remove Numbers From String in Python Using “join()” and “isdigit()” Methods

Use the “join()” and “isdigit()” built-in methods to remove the numeric value from any string in Python. The “join()” method is used to join a string with the specified iterable elements, such as a list, tuple, string, and many more. On the other hand, the “isdigit()” method checks whether the element is a string or a number.

Example

At first, create a string variable “alpha_num_str” and initialize it:

Use the “join()” and “isdigit()” functions with a “for” loop to traverse over every value from the previously created string and ignore any numeric value that exists in the string. Then, join the remaining string characters to generate a new filtered string without numeric values and save it in the new string variable:

Get the value of filtered variable through the print function:

It can be observed that the newly generated string has no numeric value:

Method 2: Remove Numbers From String in Python Using “sub()” Built-in Method

Python built-in “sub()” method can be used to delete the numeric values from the string. The “sub()” method exists in the regex module that replaces all the present of the provided pattern in the string with a particular replacement string.

Check the syntax of the “sub()” method:

  • pattern” represents the string that requires to be replaced.
  • replaceValue” is the value that will be replaced with the original value.
  • string” argument is the original string.

Example

First, import the Python built-in “re” regex module:

Then, define a desired pattern that removes numbers from “0-9” and store it in the “pattern_order” variable:

Call the “re.sub” method with required modules and pass them to the “char_str” string variable:

Print the value of the string variable:

Method 3: Remove Numbers From String in Python Using “translate()” Built-in Method

To remove the numbers from the string in Python, the built-in “string” Python library can be used. When the “string” object is passed, the “maketrans()” method splits digits from the stream of string. After that, it will create a trans-table that keeps the none value against “0” to “9” numbers. Then, this created table will be passed to the “translate()” function as an argument.

Example

Initially, import the “string” Python built-in library:

Use the “str.maketrans()” method to split digits from the stream of string by specifying the required parameters. As a result, the table will be created that includes each digit from “0-9” will be mapped to none and saved into the “trans_table” variable:

Call the “translate()” the method with particular string and pass the previously generated table as parameter:

Lastly, use the “print()” statement:

As you can see, the numbers from the desired string have been eliminated successfully:

Method 4: Remove Numbers From String in Python Using “filter()” Method

To remove the integer value from any Python string, the “filter()” function, and lambda are also used. The “filter()” method filters or removes all the numeric values from the provided string, the lambda expression as its arguments, and joins the rest of the string characters to generate a new modified string through the “join()” method.

Example

First, filter the number from the previously initialized string. Then, call the “join()” method to join all the remaining string characters and passes to the “char_str” string variable:

Call the “print()” function to get the desired filtered string:

That was all about deleting the numeric value from the string in Python.

Conclusion

To delete the number from any Python string, the “join()” and “isdigit()” methods, the “sub()” regex module method, “translate()”, and the “filter()” methods can be used. These methods first filter the string from the numeric value and then save the modified string to the new variable. This write-up explained different ways to remove the numeric value from the string in Python.

About the author

Maria Naz

I hold a master’s degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.

Источник

Оцените статью