Strings are just words or a combination of words. Python has a built-in class
str, which comes in handy while dealing with words or sentences.
Table of Contents
- How to declare a string in Python?
- Accessing string characters in Python
- String Slicing in Python
- Frequently used string methods
- Reading input from Standard Input (STDIN) in Python
How to declare a string in Python?
Strings are surrounded by either
But hey! Why does it print the quotes along-with?
Python merely outputs whatever is returned from the last statement. When we types
s, it returned the object
'susan'. To print the word ‘susan’ without quotes, python comes with
print() function. It will print the string
s as is.
Accessing string characters in Python
Each character of a string has some index value. Index values starts from 0.
We can access any character of a string by providing the index of that character.
What if we go beyond the length of the string? Let’s try it out.
Python raises an error saying that the index is out of range. How do I know what is the length of the string?
len() returns the length of string. It can also be used for many other types of objects.
With this information, one might think that I can change a string by changing the values at any index of the string. Smart! However, Python strings are immutable, which means that once declared, strings cannot be altered. If we really want to have the facility of altering a list of characters, we can use Python Lists.
However, we can use multiple strings to form another string.
String Slicing in Python
Using slicing we can extract out sub-strings of any string. We have to provide the starting index and the ending index i.e.
It starts from
start and ends right before
end. It won’t print the character at the index
end. As in the example above, we have
n at the 4th index of
"susan", however, it printed only till
Python also supports negative indexing! It means that if you want to access the last character of any string, you could simply do
So we can also slice strings using -ve indices!
start is out of the range of the string, then it prints empty string.
If you don’t provide
start, then it will print from
end is not provided, it prints till the end of string.
And if we don’t provide either of them? You guessed it right! It prints the whole string as is.
Frequently used string methods
Reading input from Standard Input (STDIN) in Python
Python built-in method
raw_input() is used to read strings from Standard Input stream
Next, we will see how to control the flow of a program depending on various conditions.
Note: This is a part of what I learned in an online Open Course Ware offered by MIT on edX. Its for my personal reference & also for those who would like to revisit the course.