Tuesday, April 23, 2024
HomeSoftware EngineeringHow you can Substitute Characters with Alphabet Positions in Python

# How you can Substitute Characters with Alphabet Positions in Python

## The problem#

Given a string, substitute each letter with its place within the alphabet.

If something within the textual content isn’t a letter, ignore it and don’t return it.

`"a" = 1``"b" = 2`, and so on.

### Instance#

``````alphabet_position("The sundown units at twelve o'clock.")
``````

Ought to return `"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"` (as a string)

## The answer in Python code#

Choice 1:

``````def alphabet_position(textual content):
return ' '.be part of(str(ord(c) - 96) for c in textual content.decrease() if c.isalpha())
``````

Choice 2:

``````def alphabet_position(textual content):
al = 'abcdefghijklmnopqrstuvwxyz'
return " ".be part of(filter(lambda a: a != '0', [str(al.find(c) + 1) for c in text.lower()]))
``````

Choice 3:

``````alphabet = 'abcdefghijklmnopqrstuvwxyz'

def alphabet_position(textual content):
if kind(textual content) == str:
textual content = textual content.decrease()
end result = ''
for letter in textual content:
if letter.isalpha() == True:
end result = end result + ' ' + str(alphabet.index(letter) + 1)
return end result.lstrip(' ')
``````

## Check circumstances to validate our resolution#

``````from random import randint

take a look at.assert_equals(alphabet_position("The sundown units at twelve o' clock."), "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11")
take a look at.assert_equals(alphabet_position("The narwhal bacons at midnight."), "20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20")

number_test = ""
for merchandise in vary(10):
number_test += str(randint(1, 9))
take a look at.assert_equals(alphabet_position(number_test), "")
``````
RELATED ARTICLES