Home > Software design >  How to link elements from a string with numbers in Python?
How to link elements from a string with numbers in Python?

Time:11-06

I'd like to link elements from a string with numbers in Python.

Users need to give an input string (one word such as "world") and then the elements of that string (here the letters of the word "world") needs to be linked to numbers starting from 0.

Then, when you give another string as an input, the corresponding numbers need to be printed.

What I tried:

# input
string = str(input())

# loop to link numbers with string input
number = -1
for letter in string:
    number  = 1

Now I'd like to link the first letter of the input string with the number 0 and so on.

E.g.:

string = "world"

than "w" = 0, "o" = 1, "r" = 2, "l" = 3 and "d" = 4.

And then when you give another string such as "lord" I want to get the following output:

3124

Because "lord" --> "l" = 3, "o" = 1, "r" = 2 and "d" = 4

I don't know how I can save these numbers to their corresponding letter.

CodePudding user response:

a = "world"

tracker = dict()
for index, value in enumerate(a):
  tracker[value] = index

b = "lord"
result = ""
for str_char in b:
  result  = str(tracker[str_char])

print(result)

CodePudding user response:

There is built-in data structure that can store key value pairs and it is called dictionary

You can make it as such:

string = "world"
letters_numbers = {}
numerator = 0

for char in string:
  if char not in letters_numbers:
    letters_numbers[char] = numerator
    numerator  = 1
    

then you can get another string, such as lord:

string2 = "lord"
numbers = []

for char in string2:
  numbers.append(str(letters_numbers[char]))

print("".join(numbers))  # prints 3124

This way you can use words that has same letter multiple times and still get correct results.

  • Related