STRING IN PYTHON
The string is a data type in Python.
The string is a sequence of characters enclosed in quotes.
We can primarily, write a string in these three ways.
- Single quoted strings - a='Suman'
- Double quoted strings - b="Suman"
- Triple quoted strings - c='''Suman'''
String Slicing
A string in python can be sliced for getting a part of the string.
Consider the following string:
name= "SUMAN" (length=5)
where,
name[0]=S name[-5]=S
name[1]=U name[-4]=U
name[2]=M name[-3]=M
name[3]=A name[-2]=A
name[4]=N name[-1]=N
Slicing a string
word = "amazing"
word[1:6] == "mazin"
word[2:5] == "azi"
Slicing with skip value
We can provide a skip value as a part of our slice like this:
word="amazing"
word[1:6:2] == 'mzn'
Advanced Slicing techniques
word="amazing"
word[:7]==word[0:7]=="amazing"
word[0:]==word[0:7]=="amazing"
String Functions
Some of the most used functions to perform operations on or manipulate strings are:
- len() function - returns the length of the string
- String.endswith("rry")- Returns true if string ends with letter rry
- String.count('c') - Counts total number of occurence of 'c' in given strings
- String.capitalize() - This function capitalize the first character of the given string.
- String. find(word) - This function finds a word and returns the index of the first occurrence of that word in the string.
- String.replace(old word, new word) - This function replaces the old world with a new word in the string.
Escape Sequence Characters
The sequence of characters after backlash '\'
The escape sequence character comprises more than one character but represents one character when used within the strings.
Examples:
\n - newline
\t - Tab
\ - single quote
\\ - backlash
Tags:
string in python