2014-02-14 22 views
0

我希望我的程序打印字符串「welcome」中的其他每個字母。 像:Python:使用循環更改範圍位置

e 
c 
m 

這裏是我到目前爲止的代碼:

stringVar = "welcome" 
countInt = 7 

count = 0 
oneVar = 1 
twoVar = 2 

showVar = stringVar[oneVar:twoVar] 

for count in range(countInt): 
count = count + 1 
oneVar = oneVar + count 
twoVar = twoVar + count 

print(showVar) 

雖然只顯示第2個字母 「e」。 我如何獲得變量oneVar和twoVar來更新,以便範圍在循環的持續時間內發生變化?

回答

4

有一個內置的符號來表示此,所謂"slicing"

>>> stringVar = "welcome" 
>>> print(stringVar[::2]) 
wloe 
>>> print(stringVar[1::2]) 
ecm 

stringVar是迭代就像一個列表,因此符號表示[start : end : step]。隱含任何一個空白從[0 : len(stringVar) : 1]假定。有關更多詳細信息,請閱讀鏈接的帖子。

0

爲什麼它在你的snipet不工作:

即使你增加oneVar和twoVar循環裏面,有在showVar沒有變化showVar是字符串,是不可改變的類型,其打印STRINGVAR [1: 2],這是ewelcome第二指數:

只是爲了解決您的片段: 你可以只是嘗試這樣;

stringVar = "welcome" 
countInt = 7 

for count in range(1,countInt,2): 
    print count, stringVar[count] 

輸出:

e 
c 
m 
+0

他不希望第二個字符:) – thefourtheye

+0

沒我把一些錯誤要麼 ?我想我正在解釋他爲什麼只得到第二個角色。 –

+0

他預計只有'e c m' – thefourtheye

0

的做同樣的另一種更復雜的方法是

string_var = "welcome" 

for index, character in enumerate(string_var, start=1): # 'enumerate' provides us with an index for the string and 'start' allows us to modify the starting index. 
    if index%2 == 0: 
     print character