Strings

Sequence of characters

In [2]:
type(a)
Out[2]:
str
In [3]:
a = 'apple'
b = "apple"
c = '''apple'''
d = """apple"""
In [4]:
a==b==c==d
Out[4]:
True
In [5]:
e = '''
line 1
line 2
'''

Properties of string

  • Case sensitive
  • Concatenation: str + str
  • Repitition : str * int
  • Immutable
  • Sequence
In [6]:
'hello' == "Hello"
Out[6]:
False
In [7]:
"abc" + "123"
Out[7]:
'abc123'
In [8]:
"ha" * 4
Out[8]:
'hahahaha'
In [10]:
x = "apple"
x[0] = 'A' # immutable
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-3729880db83b> in <module>()
      1 x = "apple"
----> 2 x[0] = 'A'

TypeError: 'str' object does not support item assignment
In [12]:
x = [1, 2, 3]
x[0] = 100 # mutable
x
Out[12]:
[100, 2, 3]
In [15]:
x = "hello"
y = x.upper()
In [16]:
x
Out[16]:
'hello'
In [17]:
y
Out[17]:
'HELLO'
In [18]:
#    01234
x = "hello"
#      -2-1
In [19]:
x[0] # indexing
Out[19]:
'h'
In [20]:
x[-1]
Out[20]:
'o'
In [21]:
x[0:3] # slicing [start=0:end-1:step=1]    [m,n)
Out[21]:
'hel'
In [22]:
x[:3]
Out[22]:
'hel'
In [23]:
x[:]
Out[23]:
'hello'
In [24]:
x[0:len(x):1]
Out[24]:
'hello'
In [25]:
x[::]
Out[25]:
'hello'
In [26]:
x[::-1] # reverse a string
Out[26]:
'olleh'
In [27]:
x == x[::-1] # pallindrome
Out[27]:
False
In [28]:
x = "madam"
In [30]:
x == x[::-1]
Out[30]:
True
In [31]:
len(x) # char count 
Out[31]:
5
In [32]:
x = "hello world"
In [34]:
len(x.split()) # word count
Out[34]:
2
In [35]:
s = input("Enter a sentance ")
s.split()
Enter a sentance India is my country
Out[35]:
['India', 'is', 'my', 'country']
In [36]:
len(s.split())
Out[36]:
4
In [37]:
x
Out[37]:
'hello world'
In [38]:
x[20]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-38-275a61224a60> in <module>()
----> 1 x[20]

IndexError: string index out of range
In [39]:
x[-20]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-39-c4830f60698b> in <module>()
----> 1 x[-20]

IndexError: string index out of range
In [40]:
x = "india is   my country"
In [41]:
x.split()
Out[41]:
['india', 'is', 'my', 'country']
In [44]:
x = "Hello"
sorted(x)
Out[44]:
['H', 'e', 'l', 'l', 'o']
In [45]:
x = "apple"
In [46]:
sorted(x)
Out[46]:
['a', 'e', 'l', 'p', 'p']
In [47]:
x = "AbBaCc" # A-Za-z
In [48]:
sorted(x)
Out[48]:
['A', 'B', 'C', 'a', 'b', 'c']
In [49]:
ord('A')
Out[49]:
65
In [50]:
ord('B')
Out[50]:
66
In [51]:
ord('a')
Out[51]:
97
In [53]:
ord('1')
Out[53]:
49
In [54]:
ord('2')
Out[54]:
50
In [55]:
chr(65)
Out[55]:
'A'

Built-in functions of string

In [56]:
dir(str)
Out[56]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']
In [57]:
x = "apple"
In [61]:
sorted(x, reverse=True)
Out[61]:
['p', 'p', 'l', 'e', 'a']
In [62]:
sorted(x)[::-1]
Out[62]:
['p', 'p', 'l', 'e', 'a']
In [63]:
x = "indIA Is grEAT"
In [64]:
x.upper()
Out[64]:
'INDIA IS GREAT'
In [66]:
x.lower()
Out[66]:
'india is great'
In [67]:
x.capitalize()
Out[67]:
'India is great'
In [68]:
x.title()
Out[68]:
'India Is Great'
In [69]:
x.swapcase()
Out[69]:
'INDia iS GReat'
In [73]:
x = "india is great"
In [74]:
x.count('i')
Out[74]:
3
In [75]:
x.count('eat')
Out[75]:
1
In [76]:
x.count('ant')
Out[76]:
0
In [77]:
x.find('eat')
Out[77]:
11
In [78]:
x.find("ant")
Out[78]:
-1
In [79]:
x.replace('i', 'K')
Out[79]:
'KndKa Ks great'
In [81]:
x.replace('i','')
Out[81]:
'nda s great'
In [82]:
x
Out[82]:
'india is great'
In [83]:
x.isupper()
Out[83]:
False
In [84]:
x.islower()
Out[84]:
True
In [85]:
x.title()
Out[85]:
'India Is Great'
In [86]:
"esgrwrgt2345".isalpha()
Out[86]:
False
In [87]:
"23534".isdigit()
Out[87]:
True
In [88]:
"sdgettq235".isalnum()
Out[88]:
True
In [89]:
"hgchg".isalnum()
Out[89]:
True

Practice

In [ ]: