Skip to content

String Operations

ZekeLabs Technologies Private Limited edited this page Nov 30, 2016 · 1 revision
>>> s1 = 'hello world'
>>> s2 = "hello world"
>>> s1[0]
'h'
>>> s1[-1]
'd'
>>> s1[-2]
'l'
>>> s1[2]
'l'
>>> s1[2:8]
'llo wo'
>>> s1[2:]
'llo world'
>>>
>>> s1 + s1
'hello worldhello world'
>>> s1 + ' ' +s1
'hello world hello world'
>>>
>>> s1
'hello world'
>>> s1[0]
'h'
>>> s1[0] = 'k'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> s1 = 'great'
>>>
>>>
>>> s1
'great'
>>> s1 * 2
'greatgreat'
>>> s1 * 5
'greatgreatgreatgreatgreat'
>>> (s1 + ' ' )* 5
'great great great great great '
>>>
>>>
>>>
>>> s = 'hello world'
>>> s[::-1]
'dlrow olleh'
>>> s
'hello world'
>>> s
'hello world'
>>> s[::-1]
'dlrow olleh'
>>>
>>>
>>> s[::-2]
'drwolh'
>>>
>>> help(str)
>>> help(str)
>>> s = 'this is a great world'
>>> s.count('is')
2
>>> s.count(' ')
4
>>>
>>> help(str)
>>> s.endswith('world')
True
>>> s = 'www.zekelabs.com'
>>> s.ends('.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'ends'
>>> s.endswith('.com')
True
>>> s.endswith('.in')
False
>>> s.startswith('www')
True
>>> s
'www.zekelabs.com'
>>> s.index('z')
4
>>> s.index('.')
3
>>> s.index('.',4)
12
>>>
>>>
>>> help(str)
>>> help(str)
>>> help(str)
>>> s.find('.',4)
12
>>> s.find('hhg',4)
-1
>>> s.index('hhg',4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>
>>>
>>> s.find('hhg')
-1
>>> s.find('.')
3
>>> s.rfind('.')
12
>>> s.rfind('.')
12
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> s = "{name}"
>>> s = "Hi, Mr {name}. Congrats you got {percent}% hike"
>>> s
'Hi, Mr {name}. Congrats you got {percent}% hike'
>>> s.format(name="Khan", percent=200)
'Hi, Mr Khan. Congrats you got 200% hike'
>>>
>>> s.format(name="Das", percent=20)
'Hi, Mr Das. Congrats you got 20% hike'
>>> s.format(percent=20,name="Das")
'Hi, Mr Das. Congrats you got 20% hike'
>>>
>>>
>>>
>>>
>>> help(str)
>>>
>>>
>>> s
'Hi, Mr {name}. Congrats you got {percent}% hike'
>>> s = '12121331'
>>> type(s)
<type 'str'>
>>>
>>>
>>> d = 121212
>>> type(s)
<type 'str'>
>>> type(d)
<type 'int'>
>>>
>>>
>>>
>>> s
'12121331'
>>>
>>>
>>> d = raw_input('User Data')
User Data
>>>
>>>
>>> d = raw_input('User Data : ')
User Data : 76876786
>>> d
'76876786'
>>> type(d)
<type 'str'>
>>>
>>> s.isdigit()
True
>>> d = raw_input('User Data : ')
User Data : 120391023r
>>> s.isdigit()
True
>>> d.isdigit()
False
>>>
>>>
>>> d = raw_input('User Data : ')
User Data : 4234234
>>> d.isdigit()
True
Clone this wiki locally