Quite often I have contact with the objects through their names, and accordingly I perform various operations with a text variable. Now I show several important things about strings in Python.

The most interesting moments in my opinion. If you have some supplements, please write in comments:

1) the length of the line. It’s quite simple – len (s)

2) You can glue the two lines through the operator + It is also quite simple – s = ‘prefix’ + s

3) an interesting point, if you want to remove the first <n> characters of the string

s = s [n:]

In this case the square brackets is given the range in which the characters will return a string. [start: end]. If you miss <start> index, the line will begin with the first character, if you miss the <end> index, the line will end the last symbol.

4) By analogy with the previous example, if you want to remove from a string of recent <n> characters

s = s [:-n]

If the index is positive, the numbering of characters starts from the begining. Otherwise, if there was a minus sing, the characters numbering starts from the end of the string.

5) to replace the part of the string

s = s.replace ( ‘camera’, ‘object’)

in this case, the line will look into substrings ‘camera’, and if successful – replaced by the ‘object’.

That’s it, good luck!

Python. String operations
Tagged on:         

2 thoughts on “Python. String operations

  • Monday March 14th, 2011 at 04:00 PM

    Hi there would you mind stating which blog platform you’re using? I’m going to start my own blog soon but I’m having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something unique. P.S Sorry for getting off-topic but I had to ask!

  • Monday March 14th, 2011 at 04:03 PM

    Hi, my blog is based on WordPress. You can see a description on the bottom of the page.

Leave a Reply

Your email address will not be published. Required fields are marked *