Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

Python 2.7 print vs return

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

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

1 Reply

0 votes
by (71.8m points)

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)])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...