如何对字符串进行切片:
word = 'these'
print word[0] # it's similar to list indexing, starts at 0
要按倒序获取字母,请使用负数:word[-1]
是最后一个字母;word[-2]
是倒数第二个,等等。
word[1:]
返回从索引 1(第二个字母)到末尾的每个字母。'word[:5] returns every letter up to index 5 (exclusive, letters 1, 2, 3, and 4).
words[1:5]` 返回从索引 1 到索引 5 的每个字母(字母 2、3 和 4)。
由于您有多条线路,因此您想要这样做,words += lines.split()
因为
untranslated = open('english.txt','r')
vowels = ('a', 'e', 'i', 'o', 'u') # I like using lists/tuples rather than strings
# if you are just checking if something is in it
newWords = []
for lines in untranslated:
words += lines.split() # this fixes the last line problem
# this assumes each word is on one line, separated by a space (like: 'these are words')
for word in words: # iterates through every word
if word[0] in vowels: # if first letter is a vowel
new_word = word + 'yay'
else:
new_word = word[1:] + word[0] + 'ay'
newWords.apend(new_word)
根据 Eric Roper 的建议,您可以创建字典作为翻译:
newWords = {}
for word in words:
if word[0] in vowels:
new_word = word + 'yay'
newWords[word] = new_word
else:
new_word = word[1:] + word[0] + 'ay'
newWords[word] = new_word
一些参考资料: