6

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?

1
  • 3
    don't use builtin chr as variable name... recipe for problems. Commented May 12, 2022 at 8:40

6 Answers 6

9

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(r'\d+', '', table)
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

3

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

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

Comments

0
table = "table123"

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

Comments

0

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)

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.