0

So, I'm working on a program which converts input text into Discords regional_indicator emoticons but the issue is that if a word is entered such as "cab" the output will return as "abc". Is there any way of changing the program so that when words are entered, they aren't sorted into alphabetical order. (I've only programmed the first 3 letters for testing purposes. Coded in Python IDLE 3.5)

import sys
sentence = input("Enter a sentence:")
sentenceLower = sentence.lower()
sentenceList = list(sentenceLower)
sentenceListLength = len(sentenceList)
while sentenceListLength > 0:
    if "a" in sentence:
        sys.stdout.write(":regional_indicator_a:")
        sentenceListLength = sentenceListLength - 1
    if "b" in sentence:
        sys.stdout.write(":regional_indicator_b:")
        sentenceListLength = sentenceListLength - 1
    if "c" in sentence:
        sys.stdout.write(":regional_indicator_c:")
        sentenceListLength = sentenceListLength - 1

In short, the program receives a sentence, checks if letters appear in that sentence and then it prints out text to be copy and pasted into Discord.

Richard Pope
  • 117
  • 5
  • I'm not sure I understand what you're trying to do, but I think you probably want to iterate over the characters in the sentence instead of looking for characters in the sentence. –  Dec 27 '17 at 02:51
  • This is a less efficient way of doing it than the least efficient way I could come up with in my head on short notice. – Mad Physicist Dec 27 '17 at 03:47

2 Answers2

2

You need to loop through the characters in the sentence rather than looping through the number of characters.

for c in sentence:
    if c == "a":
       sys.stdout.write(":regional_indicator_a:")
    elif c == "b":
        sys.stdout.write(":regional_indicator_b:")
    elif c == "c":
        sys.stdout.write(":regional_indicator_c:")

What you are doing is just checking if there exists a character in the string, so it will give you the letters back out of order.

TwoShorts
  • 508
  • 2
  • 7
  • 20
1

One way is

import sys
sentence = input("Enter a sentence:")
sentenceLower = sentence.lower()
sentenceListLength = len(sentenceLower)
for i in range(sentenceListLength) :
    c = sentenceLower[i]
    if ( ("a" <= c) and (c <= "z") ) :
        sys.stdout.write(":regional_indicator_"+c+":")
    else :
        # Do your stuff
        pass

You could as well traverse characters with

for c in sentenceLower :

instead of

for i in range(sentenceListLength) :
    c = sentenceLower[i]

(and it would be usually regarded as more pythonic). Using an integer index is sometimes more flexible/versatile (it is up to your case).