String is a data type in Python.
Strings in Python language are arrays of bytes representing Unicode characters. It means strings are the combination or collection of characters enclosed in quotes.
There are 3 type of strings in Python :
len() Function : This len() function returns the total no. of characters in a string.
E.g. a=”abc” so len(a) function will return 3 as a variable contain 3 character string.
Strings are one of the mostly used data type in any of the programming language because whenever we need data such as name, address, or any data which contain alphanumeric characters then that data type is always ‘String’.
E.g. x=“String Demo” : This string variable x contains a string and in this string there are 11 characters (including spaces) so index of this string is from 0 to length-1 of string where length = 11. So S’s index no. is 0 and t is 1 and so on.
Note : The indexes of a string begin from 0 to (length-1) in forward direction and -1,-2,-3,…,length in backward direction.
As we know the meaning of word ‘slice’ is ‘a part of’. In the same way, in Python, the term ‘string slice’ refers to a part of the string, where strings are sliced using a range of indices.
To do string slicing we just need to put name of string [n:m]. It means ‘n’ denotes the index from which slicing should start and ‘m’ denotes the index at which slicing should terminate or complete.
In Python string slicing is done in such a way i.e. n to m-1. It means from given index to given index-1.
For E.g. abc=”Demo” then abc[0:3] will give ‘Dem’ and will not give ‘Demo’ coz index no. of ‘D’ is 0, ‘e’ is 1, ‘m’ is 2 and ‘o’ is 3. So it will give range from n to m-1 i.e. 0 to 3-1=2. That’s why we got output ‘Dem’.
In string slicing we sometimes give skip value also i.e. string[n:m:skip_value].
By default the skip value is 1 but if we want to choose alternate characters of a string then we can give it as 2.
String Functions :
mystr = "Harry is a good boy" # print(len(mystr)) # print(mystr[::-2]) print(mystr.endswith("bdoy")) print(mystr.count("o")) print(mystr.capitalize()) print(mystr.replace("is", "are"))
Any Course related announcements will be posted here