-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathString Data Type.py
545 lines (446 loc) · 11.9 KB
/
String Data Type.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
'''
-----------------------------------------------------------------------STRING DATA TYPE ------------------------------------------------------------------------------------------------------
-------> What is a String?
* Any sequence of characters within either single quotes or double quoutes and triple quotes are called as String.
Example:
s = 'laptop'
s = "laptop"
single triple quote --> (''' ''')
double triple quote --> (""" """)
Note :
* Most of the other languages like c,c++ and java. A single character within character within a single quotes is treated as char data type value.
* But in python we are not having char data type. It is treated as string only.
'''
# How to access the characters of a string.
'''
1. By using index :
* Python supports both positive and negative index.
* +ve index means left to right [forward direction]
* -ve index means right to left [backward direction]
s = 'sunny'
s[0] #s
s[-1] #y
s[10] #IndexError
'''
# Basic program
s = 'sunny'
print(s[0])
print(s[-1])
print(s[10])
# 2. W.A.P to accept some string from the keyboard and display its characters by index wise both positive and negative
s = input("Enter a string: ")
i = 0
for x in s:
print("The character present at +ve index {} and -ve index{} is {}".format(i,i-len(s),x))
i += 1
# 3. By using slice operator:
s = "learning python is very easy"
print(s[1:7:1])
print(s[1:7])
print(s[:7])
print(s[:])
print(s[::])
print(s[::-1])
'''
1).If step is +ve: 2).If step is -ve:
------------------------ ------------------------
-->Forward direction(left to right) -->Backward direction(right to left)
-->Bydefault begin index is:0 -->Bydefault begin index:-1
-->Begin to End-1 -->Begin to End+1
Note:
--------
-->In the backward direction if end value is -1 then result is always empty.
-->In the forward direction if end value is 0 then result is always empty.
'''
n = '0123456789'
print(n[2:8:1])
print(n[2:8:-1])
print(n[-1:-6:-1])
print(n[2:-5:1])
print(n[-5:0:-1])
print(n[:0:-1])
print(n[2:4:-6])
# Case study
s = 'abcdefghij'
print(s[1:6:2])
print(s[::1])
print(s[::-1])
print(s[::-2])
print(s[3:7:-1])
print(s[7:4:-1])
print(s[0:1000:1])
print(s[0:1000:2])
print(s[-4:1:-1])
print(s[-4:1:-2])
print(s[5:0:1])
# print(s[9:0:0])
print(s[0:-10:-1])
print(s[0:-11:-1])
print(s[0:-12:-1])
print(s[0:0:1])
# print(s[0:0:0])
print(s[0:-9:-2])
print(s[-5:-9:-2])
print(s[9:-1:-1])
# W.A.P to access each character of string in forward direction and backward direction by using while loop.
s = input("Enter a String: ")
i = 0
n = len(s)
print("-------Forward Direction---------")
while i<n:
print(s[i],end='')
i += 1
print()
print("-------Backward Direction---------")
i = -1
while i>=-n:
print(s[i],end='')
i -= 1
print()
print("-------Backward Direction---------")
i = n-1
while i>=0:
print(s[i],end='')
i -= 1
# Another Method by using loop.
s = input("Enter a string: ")
print("---------Forward Direction----------")
for i in s:
print(i,end='')
print()
print("---------Forward Direction------------")
for i in s[::]:
print(i,end='')
print()
print("---------Backward Direction----------")
for i in s[::-1]:
print(i,end='')
'''
Checking membership:
----------------------------------
We can check whether the character or string is the member of another string or not by using in and not in operators.
'''
# Example
s = input('Enter main string:')
subs = input('Enter sub string:')
if subs in s:
print(subs,'is found in main string')
else:
print(subs,'is not found in main string')
# Comparison of strings:
# Example:
s1 = input("Enter 1st String: ")
s2 = input("Enter 2nd String: ")
if s1==s2:
print("Both are same")
elif s1<s2:
print("First string is less than second string")
else:
print("First string is greater than second string")
l1 = ['A','B','C']
l2 = ['A','B','C']
l3 = l2
print(l1 is l2)#False
print(l2 is l3)#True
print(l1 == l2)#True
'''
Removing spaces from the string:
--------------------------------------------------
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.
'''
city = input('Enter Your City:')
scity = city.strip()
if scity == 'hyderabad':
print('Hello Hyderabadi....gud mng')
elif scity == 'chennai':
print('Hello Madrasi....Vanakkam')
elif scity == 'bangalore':
print('Hello Kannadiga....Subhodaya')
else:
print('Your enetered city is invalid')
'''
Finding substring:
----------------------------
For forward direction:
-->find()
-->index()
For backward direction:
-->rfind()
-->rindex()
1.find():
s.find(substring):
Returns index of the first occurence of the given substring. If it is not availbale we will get -1.
2.index():
It is exactly same as find() method except that if the specified substring is not available then we will get ValueError.
Note:
Bydefault find() method can search total string. We can also specify the boundaries to search.
'''
s = "learning python is very easy"
print(s.find('e'))
print(s.index('e'))
print(s.find('z'))
print(s.index('z'))
print(s.rfind('e'))
print(s.rindex('e'))
print(s.rfind('z'))
print(s.rindex('z'))
print(s.find('e'))#1
print(s.find('e',2,15))#-1
print(s.find('e',2,23))#20
# W.A.P to display all the positions of substring in a given string.
s = input("Enter a string: ")
subs = input("Enter a sub string: ")
pos = -1
n = len(s)
while True:
pos = s.find(subs,pos+1,n)
if pos == -1:
break
print("Found at position: ",pos)
flag = True
if flag == False:
print("Not Found")
'''
Counting substring in the given string
---------------------------------------------------------
We can find the number of occurances of substring present in the given string by using count() method.
1).count(substring)==>It will search through out the string.
2).s.count(substring,begin,end)==>It will search from begin index to end-1 index.
'''
s = 'abbbbbbbcbabbbcba'
print(s.count('a'))#3
print(s.count('a',1,8))#0
print(s.count('ab'))#2
'''
Splitting of string:
--------------------------
We can split the given string according to specified separator by using split() method.
Syn:
l = s.split(separator)
Default separator is space. The return type of split() method is list.
'''
# Ex: 01
s = 'learning python is very easy'
l = s.split()
print(l)
for i in l:
print(i)
# Ex: 02
s = '27-07-2024'
l = s.split('-')
print(l)
for i in l:
print(i)
'''
joining of strings:
-------------------------
We can join a group of strings(list or tuple) w.r.t the given separator.
Syn:
s = separator.join(group of strings)
'''
# Example :
l = ('sunny' , 'bunny' , 'vinny' , 'cinny')
print('-'.join(l))
print(':'.join(l))
'''
Replacing a string with another string
---------------------------------------------------------
Syn:
s.replace(oldstring,newstring)
-->Inside s, every occurance of old string will be replaced with new string.
s = 'learning python is difficult'
s1 = s.replace('difficult','easy')
print(s1)
Q.String objects are immutable then how we can change the content by using replace() method?
Once we creates string object, we cant change the content. This non changable behaviour is nothing but immutability.
If we are trying to change the content by using any method, then with those changes a new object will be created and changes wont be happended in existing object.
Hence with replace() method also a new object got created but existing object wont be changed.
'''
# Example :
s = 'abab'
s1 = s.replace('a','b')
print(s,'is available at:',id(s))
print(s1,'is available at:',id(s1))
# Changing cases in a string.
s = 'learning python is very easy'
print(s.lower())
print(s.upper())
print(s.capitalize())
print(s.title())
print(s.swapcase())
# Checking starting and ending part of the string.
s = 'learning python is very easy'
print(s.startswith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))
'''
To check type of characters present in a string
----------------------------------------------------------------------
1).isalnum():Returns True if all the characters are alphanumeric(a-z,A-Z,0-9)
2).isalpha():Returns True if all the characters are only alphabate symbols(a-z,A-Z)
3).isdigit():Returns True if all the characters are digits only(0-9)
4).islower():Returns True if all the characters are lower case alphabate symbols.
5).isupper():Returns True if all the characters are upper case alphabet symbols.
6).istitle():Returns True if the string is in title case.
7).isspace():Returns True if string contains only spaces.
'''
print('sunny123'.isalnum())
print('sunny123'.isalpha())
print('sunny'.isalpha())
print('sunny'.isdigit())
print('786'.isdigit())
print('sunny'.islower())
print('sunny123'.islower())
print('SUNNY'.isupper())
print('Learning Python Is Very Easy'.istitle())
print(' '.isspace())
# Example
s = input("Enter any character: ")
if s.isalnum():
print("It is a alpha numeric character")
if s.isalpha():
print("It is a alphabet character")
if s.islower():
print("It is a lower case alphabet character")
else:
print("It is a upper case alphabet character")
else:
print("It is a digit")
elif s.isspace():
print("It is a space character")
else:
print("It is a special character")
# Q.w.a.p to reverse order of words
# 1st-way
s = input("Enter a string: ")
words = s.split()
reversed_words = words[::-1]
result = ' '.join(reversed_words)
print(result)
# 2nd way
s = input("Enter a string: ")
l = s.split()
l1 = []
i = len(l)-1
while i>=0:
l1.append(l[i])
i -= 1
print(' '.join(l1))
# Q.W.A.P to reverse the content of each word
# 1st way
s = input("Enter a string: ")
words = s.split()
result = ''
for word in words:
result = result + word[::-1] +''
print(result)
# 2nd way
s = input("Enter a string: ")
l = s.split()
l1 = []
i = 0
while i<len(i):
l1.append(l[i][::-1])
i += 1
print(' '.join(l1))
# W.A.P to print characters at odd positions and even positions for the given string
# 1st way
s = input('Enter some string:')
print('Characters at even position:',s[0::2])
print('Characters at odd position:',s[1::2])
# 2nd way
s = input('Enter some string:')
print('Characters at even position:')
i = 0
while i < len(s):
print(s[i],end='')
i += 2
print()
print('Characters at odd position:')
i = 1
while i < len(s):
print(s[i],end='')
i += 2
# Q.w.a.p to merge chraracters of 2-strings into a single string by taking characters alternatively.
# s1 = 'mahesh'
# s2 = 'sunny'
# o/p:'msauhnensyh'
s1 = input('Enter first string:')
s2 = input('Enter second string:')
i,j = 0,0
output = ''
while i < len(s1) or j < len(s2):
if i < len(s1):
output += s1[i]
i += 1
if j < len(s2):
output += s2[j]
j += 1
print(output)
# Q.w.a.p to sort the characters of the string and first alphabte symbols followed by numeric values.
# i/p:'B4A1D3'
# o/p:'ABD134'
s = input('Enter some string:')
s1 = s2 = output = ''
for x in s:
if x.isalpha():
s1 += x
else:
s2 += x
for x in sorted(s1):
output += x
for x in sorted(s2):
output += x
print(output)
# Q.w.a.p for the following requirement.
# i/p:'a4b3c2'
# o/p:'aaaabbbcc'
s = input("Enter a string: ")
s1 = ''
i = 0
while i<len(s):
char = s[i]
i += 1
num_str = ''
while i < len(s) and s[i].isdigit():
num_str += s[i]
i += 1
if num_str:
count = int(num_str)
else:
count = 1
s1 += char*count
print(s1)
# 2nd way
s = input("Enter a string: ")
output = ''
for x in s:
if x.isalpha():
output += x
previous = x
else:
output += previous * (int(x) - 1)
print(output)
# Q.Remove duplicates from the given string?
# i/p:'ABCBABCBABCBDBABCB'
# o/p:'ABCD'
s = input("Enter a string: ")
s1 = ''
for x in s:
if x not in s1:
s1 += x
print(s1)
# W.A.P for the following requirements
# i/p : 'a4k3b2'
# o/p : 'acknbd'
s = input("Enter a string: ")
output = ''
for x in s:
if x.isalpha():
output += x
previous = x
else:
output += chr(ord(previous) + int(x))
print(output)