I'm trying to change numbers in a string to an assigned letter (0 would be 'A', 1 => 'B' and so on...). For example a random combination of numbers and letters would look something like this 'a1b2c3'. The output should be 'aBbCcD'. Also, I think it's worth mentioning that this random word needs to be read from a text file and the results should be printed into a new one.
In this case I must use a function (def) to change the numbers to the assigned letter. I tried doing the program with if's in a for cycle with indices and it worked, but my professor said there is an easier and shorter solution. I tried doing it with isdigit() instead, but my function doesn't recognize the numbers in the given word and just prints out the same word (For example I input 'a1b2c3' and the output is 'a1b2c3').
CodePudding user response:
You can use a dictionary to map digits to letters, write a generator to get those letters and join it all into a resultant string. The dictionary's get
method either gets the value or returns a default. Use this to return any non-digit characters.
>>> digit_map = dict(zip('123456789', 'ABCDEFGHI'))
>>> test = 'a1b2c3'
>>> "".join(digit_map.get(c,c) for c in test)
'aAbBcC'
CodePudding user response:
Use ord
to get the numeric value of a character, and chr
to turn the numeric value back into a character. That lets you convert a number like 1
into its offset from another character.
Then use join
to put it all together:
>>> ''.join(chr(int(c) ord('A')) if c.isdecimal() else c for c in 'a1b2c3')
'aBbCcD'
CodePudding user response:
One solution would be creating an array that would store each letter as a string as such:
alphabet = ["A", "B", "C"] // and so on
Then you could loop trough the string and find all numbers, then for each numbers get the corresponding letter by accessing it from the array as such py alphabet[i]
and feed it back to the string and return that
CodePudding user response:
Here is a simple function that you can use to convert numbers to letters in a given string:
def convert_numbers_to_letters(s):
# Create a dictionary that maps numbers to letters
number_to_letter = {str(i): chr(i ord('A')) for i in range(10)}
# Iterate through each character in the string
result = ""
for c in s:
# If the character is a number, convert it to a letter
if c.isdigit():
result = number_to_letter[c]
# Otherwise, just add the character to the result
else:
result = c
return result