Active Topics

 


Reply
Thread Tools
Posts: 291 | Thanked: 398 times | Joined on Jan 2011 @ USA
#1
Hi,

I am noob in python, I need help with the syntax to trimp the string with python.

str = '187790012345'
strlen = 4
newstr = ?

I like the newstr to return only first strlen of str.... like '1877'

How do i do that in an effective way? Thanks.
 
Posts: 136 | Thanked: 150 times | Joined on Dec 2010 @ Finland
#2
http://docs.python.org/release/1.5.1p1/tut/strings.html
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word[:2] # The first two characters
'He'
>>> word[2:] # All but the first two characters
 

The Following User Says Thank You to mooglez For This Useful Post:
Posts: 291 | Thanked: 398 times | Joined on Jan 2011 @ USA
#3
Thank you very much

Will this be correct?

newstr = str[:strlen]
 
Posts: 123 | Thanked: 99 times | Joined on Sep 2010 @ Russia
#4
to trim last character?
better newstr = str[:-1]
 
Posts: 28 | Thanked: 13 times | Joined on Nov 2010 @ Tampere, Finland
#5
Originally Posted by khuong View Post
Thank you very much

Will this be correct?

newstr = str[:strlen]
Why don't you just try it. The whole point of Python is that it is an interpreted language, which makes it fast to try code snippets.

If you need to ask if a one line piece of code is ok or not, you will never get a Python program to work.
 

The Following User Says Thank You to mvuori For This Useful Post:
Posts: 2,225 | Thanked: 3,822 times | Joined on Jun 2010 @ Florida
#6
Originally Posted by khuong View Post
Thank you very much

Will this be correct?

newstr = str[:strlen]
Yes, that works. Just make sure that when you define str, it gets defined as a string instead of an integer.

For instance, typing "str = 123456789" in python will give you the integer 123456789 (one hundred twenty-three million, four hundred fifty-six thousand, seven hundred eighty nine), instead of the characters "123456789".

By the same token, make sure strlen is defined as an integer. If it gets interpreted as a string, prob'ly won't work.

Also, if this is N900 python development, you can just type "python" in the X-Terminal to get an interactive python shell from which you can test all this stuff.
 

The Following User Says Thank You to Mentalist Traceur For This Useful Post:
Reply


 
Forum Jump


All times are GMT. The time now is 15:32.