Catarina Ribeiro
Catarina Ribeiro

Reputation: 646

How to replace a number in a string in Python?

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?

Upvotes: 5

Views: 3698

Answers (6)

Adon Bilivit
Adon Bilivit

Reputation: 26935

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)

Upvotes: 8

Bendik Knapstad
Bendik Knapstad

Reputation: 1458

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

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

Upvotes: 3

Santhosh Kumar
Santhosh Kumar

Reputation: 11

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

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

Upvotes: -1

James Abela
James Abela

Reputation: 97

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)

Upvotes: 0

kylincccc
kylincccc

Reputation: 1

table = "table123"

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

Upvotes: 0

Daweo
Daweo

Reputation: 36380

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.

Upvotes: 3

Related Questions