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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

3 Comments

He doesn't want every second character :)
did i put something wrong or ? i think i was explaining why he got only 2nd character.
He expects only e c m

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.