Tuesday, 2 July 2019

String data type

String data type:

A string is a collection of characters enclosed within single quotes or double-quotes. Both are valid

Example:

If any text/numbers/alphanumeric/special characters are enclosed withing "" (double quotes) or ' (single quotes) then it is treated as a string. triple quotes are also used but when you store the more than the single sentence.

a=”Hyd”
b=”123”
c=”abc123”
d=”^%$^%#”
e=”3+4j”
f="+_&%$"
>>> f
'+_&%$'
>>> type(f)

<class 'str'>

a=”rajendra”
b=’python’
c=”””Vij is a
  cool city”””
The triple double quotes or triple single quotes are used to embed a string inside another string.

Examples:
Ex1:
>>> a="rajendra"
>>> print(a)
rajendra
>>> print(a[0])
r
>>> print(a[2])
j


Observe the following code, here I'm trying to write more than one sentence, so leads to erros to avoid this kind of situation we use triple quotes.

>>> b="vij is
  File "<stdin>", line 1
    b="vij is
             ^
SyntaxError: EOL while scanning string literal

>>> b="""vij
... is a
... cool city"""

>>> 
Ex2:

a=”vijayawada”
a[0]àv
a[20] -> Error bcoz there is no index no 20.


0
1
2
3
4
5
P
Y
T
H
O
N
-6
-5
-4
-3
-2
-1

a='python'
>>> print(a[-1])
n
>>> print(a[-5])
y
>>> print(a[-6])
p



[:] operator (slice operator) 

Slice Operator or [:] operaotor is used to access a particular part of the string.
Index starts from 0 (zero), index can be either +ve or –ve
+ve index means forward direction from left to right
-ve index means backward direction from right to left

>>> a="rajendra"
>>> a[1:5]
'ajen'

>>> 


Ex2:
>>> s="Blore"
>>> s[1:8]#it displays from 1st index to within 8th index despite there is not 8th index.
'lore'
>>> s[1:]#It display from 1st index onwards
'lore'
>>> s
'Blore'
>>> print(s)
Blore
>>> s[0:]
'Blore'
>>> s[:]
'Blore'
>>> len(s)
5
>>> 

len() :

len() is a predefined function, which is used to find the size of the string.

In python, char data type is not available. We can represent char values also by using ‘str’ data type.
ch=’m’ # it is str data type
>>> ch='m'
>>> type(ch)
<class 'str'>

To display same string with no of times we use the following way:
>>> s="raj"
>>> s*0
' '
>>> s*1
'raj'
>>> s*2
'rajraj'

>>> 

Membership operators:

in:
‘in’ is a membership operator, which checks the particular character available in the string or not. If the particular character available returns Boolean True, False otherwise.

a="Hyd"
print('y' in a)
output: True

print("k' in a)
output: False

not in: 

The 'not' is a Logical operator in Python that will return True if the expression is False. The 'not' operator is used in the if statements. If x is True, then not will evaluate as false, otherwise, True.

a="Hyd"
print('k' not in a)
True

a="Hyd"
print('y' not in a)
False


find(): 
It is a predefined function which is used to find the particular string in the string object. It returns index number if it is found, -1 means not found false otherwise.

>>> a="vij is a green city"
>>> a.find('v')
0
>>> a.find('V')
-1
>>> a.find('vij')
0
>>> a.find('vi')
0
>>> a.find('vija')
-1

a.find("is") # It returns the index number
4
>>> a.find('vij')
0
>>> a.find('cool')
9


String Special Operators:

Operator
Meaning
Ex
+
Concatenation
C=a+b
*
Repetation
a*2
[]
Slice-index
a[0]
r/R
Raw String
print
%
Format specifier: String formatting




Raw String:

Python raw string is created by prefixing a string literal with ‘r’ or ‘R’. Raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.

Which is used to suppress the actual meaning of escape sequences.  When a backslash is followed by a quote in raw string, then the escape sequences.

Examples:

Without using Raw string

S=”Hi\nGood Morning”
print(s)

Output:
Hi
Good morning

Lets use Raw string:

>>> a=r"Hi\nHello"
>>> print(a)
Hi\nHello
>>> 

Ex2:
Let’s see another example where the character followed by backslash doesn’t have any special meaning.
Now I want to print “Hi\xHello”
>>> a="Hi\xHello" or print("Hi\xHello")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \xXX escape
>>>print("Hi\xHello")

We got the error because python doesn’t know how to decode ‘\x’ as it doesn’t have any special meaning. Let’s see how we can create the same string using raw strings.

Now we can use Raw Strings:
r'Hi\xHello'
'Hi\\xHello'


When a backslash is followed by a quote in a raw string, it’s escaped. However, the backslash also remains in the result. Because of this feature, we can’t create a raw string of single backslash. Also, a raw string can’t have an odd number of backslashes at the end.

Invalid Raw strings:
r'\'  # missing end quote because the end quote is being escaped
r'ab\\\'  # first two backslashes will escape each other, the third one will try to escape the end quote.

Ex2: print(r’\n’)
#\n
Or
print(R’\n’)

Now I want to display in the following format:

Python is a “widely” used language.

>>> print("python is a "widely" used language")

SyntaxError: invalid syntax

>>> print("python is a \"widely\" used language")

"""output"""
python is a "widely" used language


Format specifier:
print("carona is a %s virus"%('dangerous'))

output:
carona is a dangerous virus

Updating the String:

>>> a="I am Rajendra"
>>> print(a)
I am Rajendra
>>> print(a[:5]+'Ravi')
I am Ravi
>>> 

A string can be updated by re-assigning a data to another string. 


Exercise:

s1 = "Python"
s1   # accessing the second character of a string
s1[3]  # accessing the  third character of a string
s1[len(s1)-1] # Accessing the length of the string and getting last character
s1[-1] # another way to accessing the last character that when we don't know
s1[-2] # accessing the penultimate character of a string

s1[0:2] # accessing the first two character  of  a string

s1[-2:] # accessing the last two character

s1[1:-1] # accessing the first and last character of a string

s1[len(s1)//2] #Accessing the middle character

s1[-1: :-1] # printing a string in reserve direction .

s1[::-2] # accessing alternate character of a string in reverse of a string

s1[::2] # accessing alternate character from start to end of string

# print the even character

#s1[-1:-3:-1] # printing the last 3 character in recerse order


Assignment:

1. What is the output of the following code ?

>>>a = "Ram Charan"
>>>a[3] = 's'
>>>print(a)
a) Ram
b) Ram Charan
c) Error
d) ramr charan

Ans: (c)

2. What is the output of the following code ?
>>>a = "Sitha"
>>>a.find("t")
a) Error
b) -1
c) 2
d) 0

Ans: (c)


Next topic      : type casting
Previous topic: Built-in Data types part 1

Click here to see related videos

You may like the following posts:
Unicode

Data types
       Sequences 
           str data type
           type casting
           Immutable
           Ordered

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(...