What is String?
Any
sequence of characters within either single quotes or double quotes is
considered as a String.
Syntax:
s='Python'
s="Python"
Note:
In
most of other languages like C, C++, Java, a single
character
with in single quotes is treated as char data type
value
. But in Python we are not having char data type.
Hence
it is treated as string only.
Eg:
ch='a'
type(ch)
<class
'str'>
How to define multi-line
String literals:
We
can define multi-line String literals by using triple
quotes.
Example:
s= ‘’’Hello
World!
Welcome to my YouTube channel !’’’
Welcome to my YouTube channel !’’’
We can also use triple
quotes to use single quotes or double quotes as symbol inside string literal.
Example 1:
s = ‘’’ MV’s Code Guide ‘’’
If your string literal has single or double
quote then it’s better to go for triple quotes to save such string literal.
Or else you can use backslash (\) before the
quotes in the literal values.
Example:
s= “MV\’s Code Guide”
Example 2:
s= ‘’’Learn
Python ‘easily’ and “efficiently” ’’’
in
the above example both single and double quotes are present in the string
literal, in this case if you want to save the string literal in single or
double quotes then using backslash is must.
S=”Learn
Python \‘easily\’ and \“efficiently\” ”
S=’
Learn Python \‘easily\’ and \“efficiently\” ’
To
avoid this extra effort of putting backslash before each and every single quote
and double quote, you can use triple quotes.
Also,
if you are importing data from some remote file then it’s not in possible for
you to take care of all the data and put backslashes in the huge data.
So,
triple quotes can be useful for that situation.
How to access characters of
a String:
We
can access characters of a string by using the following ways.
1.
By using index
2.
By using slice operator
Write
a program to accept some string from the keyboard and display its characters index
wise (both positive and negative index)
s=input("Enter
Some String:")
i=0
for x in s:
print("The character present at positive
index {} and at negative index {} is {}".format(i,i-len(s),x))
i=i+1
Accessing characters by using slice operator:
Syntax: s[beginindex : endindex : step]
beginindex: From where we have to consider slice(substring)
endindex: We have to terminate the
slice(substring) at endindex-1
step :
incremented value
Note:
·
If we are not specifying begin index then it will consider from beginning
of the string.
·
If we are not specifying end index then it will consider up to end of
the string
·
The default value for step is 1
Comparison of Strings:
We
can use comparison operators (<,<=,>,>=) and equality
operators(==,!=) for strings.
Comparison
will be performed based on alphabetical order.
s1=input("Enter
first string:")
s2=input("Enter
Second string:")
if
s1==s2:
print("Equal
Strings")
elif
s1>s2:
print("s1
is greater than s2")
else:
print("s2
is greater than s1")
Removing spaces from the
string:
We
can use the following 3 methods
1.
rstrip()---->To remove spaces at right hand side
2.
lstrip()----->To remove spaces at left hand side
3.
strip() ----->To remove spaces both sides
Finding Sub Strings:
We
can use the following 4 methods:
For forward direction:
find()
index()
For backward direction:
rfind()
rindex()
1.
find(): s.find(substring)
Returns
index of first occurrence of the given sub string. If it is not available then
we will get -1
s="Learning
Python is very easy"
print(s.find("Python"))
---------> 9
print(s.find("Java"))
-----------> -1
print(s.find("r"))---------------->
3
print(s.rfind("r"))--------------->
21
Note: By default find() method
can search total string. We can also specify the boundaries to search.
s.find(substring
, begin ,end)
It
will always search from begin index to end-1 index
Eg:
s="Learning
Python is very easy"
s.find('a',0,15)
2
s.find('r',4,20)
-1
s.find('r',4,22)
21
s.find('a',4,22)
-1
index() method:
index() method is exactly same as find() method
except that if the specified substring is not available then we will get
ValueError
Counting substring in the
given String:
count(): to count the number of occurrences of
substring in original string
1.
s.count(sub_string) : It will search
through out the string
2.
s.count(sub_string, begin, end) : It will search from begin index to end-1
index
Replacing a string with
another string:
s.replace(oldstring,newstring):
to replace every occurrence of oldstring with newstring inside the string s and
return a new string with these changes
Splitting of Strings:
We can split the given
string according to specified seperator by using split() method.
l=s.split(seperator)
The default seperator is
space. The return type of split() method is List
Joining of Strings:
We can join a group of
strings(list or tuple) with respect to the given separator.
s=separator.join(group of
strings)
l=['apple','boy','cat','dog']
>>> s="#".join(l)
>>> print(s)
apple#boy#cat#dog
>>> s="#".join(l)
>>> print(s)
apple#boy#cat#dog
Changing case of a String:
We
can change case of a string by using the following 4 methods.
1.
upper()---->To convert all characters to upper case
2.
lower() ----->To convert all characters to lower case
3.
swapcase()-----> converts all lower case characters to upper case and all
upper case characters to lower case
4.
title() -----> To convert all character to title case. i.e. first character
in every word should be upper case and all remaining characters should be in
lower case.
5.
capitalize() ----> Only first character will be converted to upper case and
all remaining characters can be converted to lower case
Checking starting and ending
part of the string:
Python
contains the following methods for this purpose
1.
s.startswith(substring)
2.
s.endswith(substring)
To check type of characters
present in a string:
Python
contains the following methods for this purpose.
1)
isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0
to9 )
2)
isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to
Z)
3)
isdigit(): Returns True if all characters are digits only( 0 to 9)
4)
islower(): Returns True if all characters are lower case alphabet symbols
5)
isupper(): Returns True if all characters are upper case alphabet symbols
6)
istitle(): Returns True if string is in title case
7)
isspace(): Returns True if string contains only spaces
Formatting the Strings:
We
can format the strings with variable values by using replacement operator {}
and format() method.
Eg:
name='Ram'
salary=10000
age=42
print("{}
's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is
{2}".format(name,salary,age))
print("{x}
's salary is {y} and his age is {z}" .format(z=age , y=salary,x=name))
Output:
Ram's salary is 10000 and his age is 48
Ram's salary is 10000 and his age is
48
Ram
's salary is 10000 and his age is 48
No comments:
Post a Comment