Skip to content
Advertisement

How can you change a particular letter to a number?

How can you change a particular letter to a number?

programming Language -> Python

# english instgram follower version
word1 = "1.9M"
word2 = "20.4K"
word3 = "5.3K"

How do you replace ‘K’ with an integer in a string value stored in a variable?

  • K = 1000

Advertisement

Answer

You can use regex –

import re
regex = re.compile("(\d{0,}.\d{0,})(M|K)")
testString = "1.23M"
matchArray = regex.findall(testString)
map_dict = {'k': 1000, 'K': 1000, 'm': 1000000, 'M': 1000000}
result = float(matchArray[0][0]) * map_dict[matchArray[0][1]]

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement