'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?
Solution 1:[1]
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)
Solution 2:[2]
If you dont want to import any modules you could try:
table = "".join([i for i in table if not i.isdigit()])
Solution 3:[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 str
s, third (optional) argument is characters to remove.
Solution 4:[4]
char_nums = [chr for chr in table if chr.isdigit()]
for i in char_nums:
table = table.replace(i, "")
print(table)
Solution 5:[5]
table = "table123"
for i in table:
if i.isdigit():
table = table.replace(i, "")
print(table)
Solution 6:[6]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Albert Winestein |
Solution 2 | MoRe |
Solution 3 | Daweo |
Solution 4 | Santhosh Kumar |
Solution 5 | quest |
Solution 6 |