How to replace a number in a string in Python?

Viewed 296

I need to search a string and check if it contains numbers in its name. If it does, I want to replace it with nothing. I've started doing something like this but I didn't find a solution for my problem.

table = "table1"

if any(chr.isdigit() for chr in table) == True:
    table = table.replace(chr, "_")
    print(table)

# The output should be "table"

Any ideas?

6 Answers

You could do this in many different ways. Here's how it could be done with the re module:

import re

table = 'table1'

table = re.sub('\d+', '', table)

If you dont want to import any modules you could try:

table = "".join([i for i in table if not i.isdigit()])

This sound like task for .translate method of str, you could do

table = "table1"
table = table.translate("".maketrans("","","0123456789"))
print(table) # table

2 first arguments of maketrans are for replacement character-for-character, as it we do not need this we use empty strs, third (optional) argument is characters to remove.

char_nums = [chr for chr in table if chr.isdigit()]

for i in char_nums:
    table = table.replace(i, "")
print(table)
table = "table123"

for i in table:
    if i.isdigit():
        table = table.replace(i, "")
print(table)

I found this works to remove numbers quickly.

table = "table1"
table_temp =""
for i in table:
   if i not in "0123456789":
      table_temp +=i
print(table_temp)
Related