String in Python - Programmrs

 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.

  1. Single quoted strings - a='Suman'
  2. Double quoted strings - b="Suman"
  3. Triple quoted strings - c='''Suman'''
String in Python

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


Slicing the 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:

  1. len() function - returns the length of the string
  2. String.endswith("rry")- Returns true if string ends with letter rry
  3. String.count('c') - Counts total number of occurence of 'c' in given strings
  4. String.capitalize() - This function capitalize the first character of the given string.
  5. String. find(word) - This function finds a word and returns the index of the first occurrence of that word in the string.
  6. 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


Post a Comment

Previous Post Next Post