Strings
String is a data type in python. String is a sequence of characters enclosed in quotes.
We can primarily, write a string in these three ways :
- Single quoted strings ➡️ a = 'Aariz'
- Double quoted strings ➡️ b = "Aariz"
- Triple quoted strings ➡️ c = "'Aariz"'
String Slicing
A string in python can be sliced for getting a part of the string.
Consider the following string:
name = "Aariz" ➡️ length = 5
↑↑↑↑↑
01234
The index in a string starts from 0 to (length-1) in Python. In order to slice a string, we use the following syntax:
sl = name[int_start:int_end]
↙️ ↘️
first index included last index is not included
sl = [0:3] returns "Aar" ➡️ characters from 0 to 3 index
sl = [1:3] returns "ar" ➡️ characters from 1 to 3 index
Negative indices: Negative indices can also be used as shown above. -1 corresponding to the (length-1) index, -2 to (length-2).
Slicing with skip value
We can provide a skip value as a part of our slice like this :
word = "amazing"
word[1:6:2] ➡️ 'mzg'
Other advanced slicing techniques:
word = "amazing"
word[:6] ➡️ word[0:6] ➡️ ''amazing"
word[0:] ➡️ word[0:6] ➡️ "amazing"
Strings functions
Some of the mostly used functions to perform operations on or manipulate strings are:
1. len() function ➡️ This function returns the length of the string
len("Aariz") ➡️ returns 5
2. string.endswith("riz") ➡️ This function tells whether the variable string ends with the String "riz" or not. if the string is "Aariz", it returns true for "riz" since Aariz ends with riz.
3. string.count("c") ➡️ Counts the total number of occurrence of any character.
4. string.capitalize() ➡️ This function capitalizes the first character of a given string.
5. string.find(word) ➡️ This function finds a word and returns the index of first occurrence of that word in the string.
6. string.replace(oldword, newword) ➡️ This function replaces the oldword with newword in the entire string.
Escape Sequence characters
Sequence of characters after backslash '\' ➡️ Escape Sequence characters
Escape sequence character comprises of more than one character but represents one character when used within strings.
Examples \n, \t, \\ etc. You can google for more.
↙️ ⬇️ ↘️
newline tab backslash
Comments
Post a Comment