How can you change a particular letter to a number?
programming Language -> Python
JavaScript
x
5
1
# english instgram follower version
2
word1 = "1.9M"
3
word2 = "20.4K"
4
word3 = "5.3K"
5
How do you replace ‘K’ with an integer in a string value stored in a variable?
- K = 1000
Advertisement
Answer
You can use regex –
JavaScript
1
8
1
import re
2
regex = re.compile("(\d{0,}.\d{0,})(M|K)")
3
testString = "1.23M"
4
matchArray = regex.findall(testString)
5
map_dict = {'k': 1000, 'K': 1000, 'm': 1000000, 'M': 1000000}
6
result = float(matchArray[0][0]) * map_dict[matchArray[0][1]]
7
8