Let's go through review, where we understand how conditionals works. How to apply if-function. How to write algorithms, where Computers make decisions, based on the user request.
Python has a set of built in functions that you can use on strings. Remember, All string functions returns new values. They do not change the original string.
There are many operations that can be performed with strings which makes it one of the most used data types in Python. We will discuss some string functions in this chapter and
other many more string functions will be discussed in further detain in coming chapters.
in: -- in returns True if the first string is contained in the second string. For instance:
"ello" in "Hello" -------> True
"UPPER" in "supper" ------> False
" " in "Hi there!" ----> True
"bear" in "ear" --------> False
len returns the number of characters in the given string:
len("hello") ----> 5len("")-----> 0len(" ")-----> 1len("test") >= 5 ----> False.lower() returns a copy of the string in all lowercase. But it doesnot odify the original string.
"Hello".lower() -------> hello
"Hello".upper()-----> HELLO
.islower() returns whether the string contains ONLY lowercase characters.
"Hello".islower() ----> False
.isupper() returns whether the string contains ONLY uppercase characters.
"HELLO".isupper()-----> True
There are many more string functions that are useful. For instance: .isdigit(), .isalnum(), .find() and many more.
We can access individuals characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError. Python allows negative indexing for its sequences. For instance; the index -1 refers to the last item, -2 to the second last item and so-on. We can access a range of items in a string by using the slicing operator:(colon).
#Accessing string characters in python:
str = "programming";
print("str = ", str);
#access first character
print("str[0] = ", str[0]) -----> p
#access last character
print("str[-1] = ", str[-1]) -----> g
#Slicing 2nd to 5th character
print("str[1:5] = ", str[1:5]) ----->rogr
#slicing 6th to 2nd last character
print("str[5:-2] = ", str[5:-2]) ---->ammi
***If you try to access an index out of range or use numbers other than an integer, we will get errors.
#index must be in range
print(str[15])-----> Index Error, string out of index.
#index must be an integer.
print(str[1.5])-----> Index Error, string indices must be integers.