Reputation: 646
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
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
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
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
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
Reputation: 1
table = "table123"
for i in table:
if i.isdigit():
table = table.replace(i, "")
print(table)
Upvotes: 0
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 str
s, third (optional) argument is characters to remove.
Upvotes: 3