开发者

python functions returning certain number of characters?

I have to create a function that when a string is inputted, the function checks to see if there are 160 character. If there are less than or开发者_JS百科 equal to 160, then print the message. If not, it has to only print the first 160. This is what i have so far:

 def message():
     message1=raw_input('input a message')
     if ((len(message1))<=160):
         return message1
     else:
        return

i do not know how to program "only return the first 160 characters of message1" Any help is appreciated!

ALSO how would i be able to change the restriction to only printing the first twenty words?


A string is just a list of characters... so you can do something like this:

def message():
    message1=raw_input('input a message')
    return message1[:160]


You can use python's slicing syntax for that:

 def message():
      message1=raw_input('input a message')
      return message1[:160]

that means, just return the first 160 characters.


Assuming this is a homework assignment, look up the concept of slicing.

Also note that when you slice, you don't have to check to see how long the string is first. You can just ask for the first 160 characters and, if there aren't that many, you'll only get as many as there are.


This will do it, but there are better ways as well

if(len(message1)<=160)
    return message1
else:
    return message1[:160]   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜