0

I would like my program to print every other letter in the string "welcome". like:

e
c
m

Here is the code I have so far:

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)

Though it only shows the 2nd letter "e". How can I get the variables oneVar and twoVar to update so that the range changes for the duration of the loop?

Sinfamy
  • 11
  • 5

3 Answers3

4

There is a built in notation for this, called "slicing":

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

stringVar is iterable like a list, so the notation means [start : end : step]. Leaving any one of those blank implicitly assumes from [0 : len(stringVar) : 1]. For more detail, read the linked post.

Community
  • 1
  • 1
mhlester
  • 22,781
  • 10
  • 52
  • 75
0

Why its not working in your snipet:

Even though you increase oneVar and twoVar inside the loop, there is no change in the showVar as showVar is string which is immutable type, and its printing stringVar[1:2] which is e the 2nd index of welcome:

Just to fix your snippet: You can just try like this;

stringVar = "welcome"
countInt = 7

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

Output:

e
c
m
James Sapam
  • 16,036
  • 12
  • 50
  • 73
0

Another more complex way of the doing the same would be

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
JRajan
  • 672
  • 4
  • 19