2

Im looking to remove every single number in a string. More specifically, i'm looking to remove all numbers in the following codes string

Comp_String = "xxf1,aff242342"

how can one do this. (Obviously inside the code). I have found many answers to questions about removing the actual parts of the code that are letters but not numbers. Please explain aswell what your code is actually doing

Wavegunner232
  • 61
  • 1
  • 2
  • 9

3 Answers3

6

You can find the answer here Removing numbers from string

From this answer:

comp_string = "xxf1,aff242342"
new_string = ''.join([i for i in comp_string if not i.isdigit()])

It creates a new string using .join from a list. That list is created using a list comprehension that iterates through characters in your original string, and excludes all digits.

Community
  • 1
  • 1
Reen
  • 399
  • 1
  • 5
  • 12
2

This will remove any characters that ARE NOT letters, by going through each character and only adding it to the output if it is a letter:

output_string = ""

for char in Comp_String:
    if char.isalpha():
        output_string = output_string + char

This will remove any characters that ARE numbers, by going through each character and only adding it to the output if it is not a number:

output_string = ""

for char in Comp_String:
    if not char.isdigit():
        output_string = output_string + char
Resin Drake
  • 528
  • 4
  • 9
0

You can do it with regular expressions using the https://docs.python.org/3.6/library/re.html module. The only regex you need is \d, which notates digits.

from re import sub

comp_string = "xxf1,aff242342"
print(sub(pattern=r"\d", repl=r"", string=comp_string))
seenorth
  • 17
  • 1
  • 9