所以,我正在研究一个将输入文本转换为Discords regional_indicator表情符号的程序,但问题是如果输入一个单词,例如" cab"输出将返回" abc"。是否有任何更改程序的方法,以便在输入单词时,它们不会按字母顺序排序。 (我只编写了前3个字母用于测试目的。用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
简而言之,该程序收到一个句子,检查该句子中是否出现字母,然后打印出要复制并粘贴到Discord中的文本。
答案 0 :(得分:2)
你需要遍历句子中的字符,而不是循环遍历字符数。
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:")
你正在做的只是检查字符串中是否存在字符,这样就会不按顺序返回字母。
答案 1 :(得分:1)
一种方法是
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
您也可以使用
遍历字符for c in sentenceLower :
而不是
for i in range(sentenceListLength) :
c = sentenceLower[i]
(它通常被视为更加pythonic)。使用整数索引有时更灵活/更通用(这取决于您的情况)。