Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to grab every other letter from a string but i'm having some problem with print and return. Why when i use print, the output is what i want and when i use return i only get the first letter?

string_bits(Hello)  # Return string made of every other char starting with the first

def string_bits(str):
    x = len(str)
    for i in range(0,x,2):
        print str[i]

output: H
        l
        o

vs

def string_bits(str):
    x = len(str)
    for i in range(0,x,2):
        return str[i]

output: H
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

As everyone has pointed out, your function returns the instance on the first loop. You can use a temporary variable to store your result and return that result.

You can use the statement below inside a function:

return ''.join([ur_string[i] for i in range(0, len(ur_string), 2)])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...