Home > front end >  convert word to letter
convert word to letter

Time:05-05

Code:

mapping = {'hello':'a', 'world':'b'}
string = 'helloworld'
out = ' '.join(mapping.get(s,s) for s in string.split())
print(out)

what I want to happen is that string = 'helloworld'gets printed as ab

what I get as the output is 'helloworld'

the reason is I don't have a space between the string hello and world but I don't want a space in-between them can anyone help?(new to python)

CodePudding user response:

A crude solution in this case would be to simply replace according to the mapping.

def replace(s, mapping):
    for k, v in mapping.items():
        string = string.replace(k, v)
    return string

CodePudding user response:

You get the output helloworld because string.split() from your code returns 'helloworld', which is what you already had to start with. The split does nothing because split, by default, will split a string by a space; of which there are none in your string.

>>>'helloworld'.split()
['helloworld']

If you change the following line, you will get a b as your output.

string = 'hello world'

I am going to assume that you say that you "don't want a space in between them", you mean that you don't want a space between a and b. To achieve that, change the following line:

out = ''.join(mapping.get(s,s) for s in string.split())

This will output ab

  • Related