Python is a scripting language which is a popular one and easy to learn. But it is also used to do more complex task and applications. With its extensive library and frameworks available we can do any kind of application with low development time and maintenance cost. Here i have discussed some of the basic operations you can do with strings in python.
String in Python
Strings in python are immutable. It means that once it is created it cannot be changed. But it can be accessed in many ways. A string is stored with a sequence of character in the memory. Each character of the string is stored in memory with a starting index of 0 to n-1. where n is the length of the string.
String index representation
The string’s characters is stored using index. You can access the individual characters of the string using the Indexing operation. Above we have a string s declared with the value ‘python’. The length of the string is 6 so the index is from 0 to 5. Now to access the characters in the string we use the following index operation. The syntax is very similar to accessing array values if you have learned C or C++.
The following code uses indexing operation to access the string characters.
''' declaring a string ''' s = "python" ''' Access the first character in the string using indexing operation ''' print(s) ''' Access characters from 0 to 4 (i.e 0 to 4-1) index characters ''' print(s[0:4]) ''' Access all the element starting from 0 ''' print(s[0:]) ''' Access the last character from the string ''' print(s[-1]) ''' Access all element except the last ''' print(s[:-1])
This is the output of the above program
>>> p pyth python n pytho
The above code was executed in python 3.2.3 console.