Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a number in a string in Python?

Tags:

python

replace

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?

like image 751
Catarina Ribeiro Avatar asked Sep 01 '26 00:09

Catarina Ribeiro


1 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(r'\d+', '', table)
like image 103
Ramrab Avatar answered Sep 02 '26 14:09

Ramrab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!