Strings in python are one or more characters surrounded by either single quotation marks, or double quotation marks
You can display a string literal with the print() function:
Traversing a String: Visit each character on a string in called traversing
Print each character of string in one line
s="Computer"
for i in s:
print(i)
Print all characters of string in single line
s="Computer"
for i in s:
print(i,end="")
Indexing
In Python, strings are ordered sequences of character data, and thus can be indexed in this way.
Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ([]). the number is called index
String indexing in Python is zero-based: the first character in the string has index 0, the next has index 1, and so on. The index of the last character will be the length of the string minus one(n-1) .
String indices can also be specified with negative numbers, in which case indexing occurs from the end of the string backward: -1 refers to the last character, -2 the second-to-last character, and so on.
String Operators:
(1) Concatination(+):
+ operator creates a new string by joining the two strings because strings are immutable.
"a"+"b" ---> 'ab'
"muk"+"esh" -----> "mukesh"
"kumar"+"mukesh" ---> "kumarmukesh"
Note: you cannot combine string with integer
"muk"+"168" --> "muk168"
"muk"+168--> give Type error : cannot concatinate str with int object
"5"+"6"---> 56
5+6--->11
(2) String Replication Operator(*) :It is useful for repeating strings to a certain length.
> "RAM" * 3
> RAMRAMRAM
>>"2"*3
222
>>>"2" * "3"
Type error: cannot multiply non int of type str
(3) Membership Operators(in and not in ):
in: returns true if given character or sub string is the part of given string
not in : returns true if given character or sub string is not the part of given string
"in" in India-----> False
"in in "india"----> True
"a" in " india" ----> True
a="12"
b="123452"
a in b----> True
(4) comparison Operators(relational operators): works with strings
"a" == "a" ----> returns True
"A" =="a" ----> returns False
"Abc"=="abc" ----> returns False because one letter case is different
ord(): returns the UNICODE(ASCII) value of each character
Characters "a" to "z" having ordinal value 97 to 122
Characters "A" to "Z" having ordinal value 65 to 90
Characters "0" to "9" having ordinal value 48 to 57
"a" >"A" returns True ( compare unicode value of character)
"ABC" > "AB" returns True
"ABCD" > "abcd" returns False
"ABCd" > "ABCD" returns True
chr( ) : Returns the character value of given integer (ordinal value )
chr(65) ----> "A"
char(97) -----> "a"
String Slicing
Python also allows a form of indexing syntax that extracts substrings from a string, known as string slicing. If s is a string, an expression of the form s[m:n] returns the portion of s starting with position m, and up to but not including position n
Syntax:
s[start:stop] # items start through stop-1
s[start:] # items start through the rest of the array
s[:stop] # items from the beginning through stop-1
s[:] # a copy of the whole array
s[start:stop:step] # start through not past stop, by step
a="abc"
a[:]
'abc'
a[::-1]
'cba'
a[0:3:]
'abc'
a[0:2:]
'ab'
a[-2:]
'bc'
s="mukesh"
s[0:3:1]
'muk'
s[1:4:1]
'uke'
s[:4:]
'muke'
s
'mukesh'
s[::-1]
'hsekum'
s[1:6:2]
'ueh'
s[:]
'mukesh'
s[:-4:-1]
'hse'
String Manipulation functions
a="computer Science"
len(a) : returns the length of string
16
a.capitalize(): capitalize first character of first word
'Computer science'
a.title(): capitalize first character of all words in string
'Computer Science'
a.upper(): convert all characters in upper case
'COMPUTER SCIENCE'
a.lower(): convert all characters in lower case
'computer science'
a.isupper(): returns true if string contain all upper case alphabet
False
a.islower(): returns true if string contain all lower case alphabet
False
s="python progamming"
b="abc123"
c="123"
s.isalnum():
returns true if all characters in string are alphanumeric
False
b.isalnum()
True
c.isalnum()
True
s.isdigit(): return true if all characters in string are digits
False
c.isdigit()
True
s.isalpha(): returns true if all character in string are alphabets
False
c.isalpha()
False
"computer".isalpha()
True
startswith() : returns true if string start with given sub string otherwise false
s="computer"
s.startswith("com")
True
s.startswith("cm")
False
endswith(): returns true if string ends with given sub string otherwise false
s.endswith("com")
False
s.endswith("ter")
True
istitle(): returns true if string has the title case
s.istitle()
False
"Computer".istitle()
True
replace():replace one part of string with another
a="Computer Science"
a.replace("Computer","Social")
'Social science'
split(): split the string and return a list
a=" I LOVE MY INDIA "
a.split()
['I', 'LOVE', 'MY', 'INDIA']
s="my name is mukesh"
s.split()
['my', 'name', 'is', 'mukesh']
s.split("m")
['', 'y na', 'e is ', 'ukesh']
partition() :
It will only split the string at the first occurrence of the given argument.
return a tuple contain only three substrings
must require one argument
return a tuple
s.partition("name")
('my ', 'name', ' is mukesh')
join():
Join all items of a list or tuple into a string, using a hash character as separator:
a=["A","B","C"]
"->".join(a)
'A->B->C'
"@".join(a)
'A@B@C'
find(): returns the lower index in the string where sub string is found. Otherwise return -1
s.find("india")
-1
s.find("INDIA")
10
index(): returns the lower index in the string where sub string is found. Otherwise give Value error
s.index("india")
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
s.index("india")
ValueError: substring not found
s.find("INDIA")
10
Note:
Python find() produces -1 as output if it is unable to find the substring, whereas index() throws a ValueError exception.
count():
Return the number of times the substring appears in the string