There are so many things that you can do and that too very efficiently with strings in Python. These all operations can be done very easily using indexing and slicing of strings in Python.
So, we will start with a basic concept that “EVERYTHING IN PYTHON IS OBJECT“. So, for strings there is an object in Python called ‘str’. So what constitutes a string in Python ?
- Any literal inside a “” or ‘’ is treated as string in Python.
To find the length of the string, there is a len() method. For Example,
Indexing of Strings
- Indexing allows to access individual characters from a string. All indexing in python starts from Zero. For example, when we write ‘hello' into the interpreter, it will give output string ‘h’.
- Negative numbers are used to index from the end of a string. For example, the value of ‘hello'[-1] is ‘o’.
Let’s see some examples:
Slicing of Strings
Slicing is used to extract substrings of arbitrary length. If str is a string, then an expression str[start:end] denotes the substring of str that starts at index start and ends at index end-1. For example, ‘hello'[1:4] = ‘ell’. Time for some examples now.
From above example, we can note that if we are not providing any slicing parameter then the substring is equal to the original string. Another example.
Let’s go for one more example, in which we will see one more parameter that you can use with slicing. Using this parameter we can reverse a string with just a single line of code.
We can reverse the string by setting the value of third parameter as -1.
Let us use the third parameter with a step size.
It prints all the characters at index position 2,4 and 6 but only up to the sample’s end index of 7 which is (8-1=7).
Let us use the third parameter to print the string from end to first but with step size of 1.
One more variant in previous example.
Python string slicing also works with negative indexes. Following example shows that.
What happens over here is that the indices are taken in reverse order i.e. it starts to print from eighth character(a) from reverse as index of last character(g) in reverse order is -1 so the index of eighth character (a) in reverse is -9 and python runs up to end-1, so it runs up to third character(l) which has index of -3=-2-(-1).
Following figure shows how does the indexing work.
Now let’s see that how can you capture input from the user in Python. If you are working with Python 2 you’ve got two methods for it and if in Python 3, you have only one method for it. In Python 2, you’ve raw_input() and input() while in Python 3 you only have the later one i.e. input().
raw_input() vs input()
- Each of these takes strings as input and displays it as a prompt in the shell, and then waits for the user to type something, which is followed by hitting enter key.
- For raw_input, the input line is treated as a string and becomes the value returned by the function; input treats the typed line as a Python expression and infers a type.
- Any input that you enter to these functions it considered of str type only.
Guys, time to go for examples of both.
Example of raw_input():
Example of input():
Seeing both the examples, you see the difference in both the functions, as mentioned above, raw_input() just takes everything as a string and prints it out without doing any kind of processing, while input() processes everything as an expression and prints out it evaluated value.
Type-Casting in Python
One more thing is type-casting in Python, we can cast the input entered by the user in any required object-type by casting in the type of object that is required by us but how to do it?
In Python, we use the name of a type to convert values to that type. So, for example, the value of int(‘3’)*4 is 12. When a float is converted to an int, the number is truncated (not rounded), e.g., the value of int(3.9) is the int 3.
There are two-types of type-conversions in Python:
- Explicit Conversion: In explicit conversion, users convert the data type in to their required type using int(), float(), str(), etc.
- Implicit Conversion: In implicit conversion, the python interpreter itself converts the lower data type to greater data type.
Let us take proper examples for the same.
Example of Explicit Type Conversion:
What we did here is that first we declared two variables both carrying some numeric value, but one of them carrying numeric value (int_num) in the form of integer and the other one (str_num) in the from string. Then we casted the str_num to int_num which is from greater type to lower type. We did this in order to perform the addition.
Now we go for the example on implicit conversion:
In this example what we did was, we took two variables, int_num and float_num for adding both of them to a variable called addition. From the output, you would find that the types of all the variables are preserved and addition operation is also being carried out successfully. Although, you can see that the type of addition is float and not integer. This is because always the greater type is assigned to a new variable or newly type-casted variable instead of the lower type. In order to assign a lower type to the new variable, you will require explicit conversion as we did in previous example.
In this post, we have discussed about indexing and slicing of strings in python with different examples. So that’s all as far as this post is concerned, in next post we will discuss about built-in data types of python as well as start to work with functions.
Other Important Topics:
- Python and Other Object-Oriented Programming Languages
- Python 2 vs Python 3
- Introduction to Python Programming
- The Basic Elements of Python Programming
- Branching, Indentation, Looping and Control Structure in Python
- Indexing & Slicing of Strings and Capturing Inputs
- Built-in Data Types and Functions in Python
- Specifications, Global Variables, Modules and Packages in Python
- Working with Files in Python
- Strings in Python
- Lists in Python
- Tuples in Python
- Dictionaries in Python
- Mutable and Immutable Python Objects
- Functions as Objects, map(), filter() and reduce()
- Exception Handling in Python
- Classes and Object Oriented Programming in Python
- Searching Algorithms in Python
- Method Resolution Order (MRO) in Python
- Sorting Algorithms in Python