user747408
user747408

Reputation: 1

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 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?

Upvotes: 0

Views: 2149

Answers (4)

coryjacobsen
coryjacobsen

Reputation: 1018

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]

Upvotes: 3

kindall
kindall

Reputation: 184345

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.

Upvotes: 1

eduffy
eduffy

Reputation: 40232

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.

Upvotes: 2

Aater Suleman
Aater Suleman

Reputation: 2328

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

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

Upvotes: 0

Related Questions