-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9.String.py
More file actions
597 lines (287 loc) · 10 KB
/
9.String.py
File metadata and controls
597 lines (287 loc) · 10 KB
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# ==================
# Strings in Python
# ==================
# Strings are immutable (cannot change characters inside them)
name = "Jackal"
print(name)
print(type(name)) # <class 'str'>
# Printing a string with quotes inside
print("He said, \"I want to eat an apple\"")
# Multi-line string using triple quotes
print('''
Conditional Statements in Python
Comments:
Conditional statements execute code only if certain conditions are True.
''')
# Accessing characters by index
newName = "Alex"
print(newName[0]) # 'A'
print(newName[1]) # 'l'
print(newName[2]) # 'e'
print(newName[3]) # 'x'
# Loop through each character in a string
for char in newName:
print(char)
# ===================
# String Slicing
# ===================
#! Format: string[start:end:step] ; end index not included
s = "Python"
print(s[0:2]) # Py
print(s[2:]) # thon
print(s[:3]) # Pyt
print(s[-3:]) # hon
print(s[:]) # Python (whole string)
print(s[0:len(s)-2]) # Pyth
print(s[-3:-1]) # ho
print(s[-4:-2]) # th
print(s[::-1]) # nohtyP
# Length of string
print(len(s)) # 6
#! Changes done using methods create a new string orignal remains the same
v = "Hello"
k = v.upper()
print("k : ", k)
print("v : ", v) #Orignal remains the same
# Convert to upper and lower case
print("cat".upper()) # CAT
print("DOG".lower()) # dog
# Remove spaces from start and end
m = " hi "
print(m.strip()) # hi
f = "!!!!Hello!!!!!!"
print(f.strip("!"))
# Replace a substring with another (all occurence changes with new)
z = "Hello, Jackal"
print(z.replace("Jackal", "Python")) # Hello, Python
# Split string into a list of words (str to list)
print("hi hello hey".split()) # ['hi', 'hello', 'hey']
# Join list of strings into one string with separator
print("-".join(["a","b","c"])) # a-b-c
# Find the index of first occurrence of a character
g = "Hello"
print(g.find("e")) # 1
# Count occurrences of a character
print("banana".count("a")) # 3
# Check if string starts or ends with a substring
print("python".startswith("py")) # True
print("python".endswith("on")) # True
str1 = "Welcome to the Console !!!"
#! endswith("to", 4, 10) → checks if substring from index 4 to 10 ends with "to"
print(str1.endswith("to", 4, 10))
# capitalize() turns first letter of the word to uppercase and else into lowercase
blogHeading = "introduction to Python Learning"
print(blogHeading.capitalize())
blogHeading = "introduction tO PythoN Learning"
print(blogHeading.capitalize())
# center() method is used to center-align a string within a specified width
text = "Hello"
print(text.center(11))
text = "Hello"
print(text.center(146, "*"))
# index() finds the position (index number) of the first occurrence of a substring-
# inside a string.
# If the substring is not found, it gives an error (ValueError).
text = "banana"
print(text.index("a")) #output 1
# Find next occurrence
text = "banana"
print(text.index("a", 2)) #Output 3
# Using start and end
text = "Hello World"
# Searches "o" only in "World" part.
print(text.index("o", 5, 10)) #Output 7
text = "hello"
# print(text.index("z")) # ERROR
# isalnum() is a string method in Python that checks if all characters in the string-
# are either alphabets (a–z, A–Z) or numbers (0–9).
s = "Hello123"
print(s.isalnum()) #Output True
s = "Hello 123"
print(s.isalnum()) #Output False
s = "12345"
print(s.isalnum()) #Output True
# isalpha() checks if all characters in the string are alphabets only (a–z or A–Z).
s = "Python"
print(s.isalpha()) #Output True
s = "Hello World"
print(s.isalpha()) #Output False
# islower() checks if all the alphabetic characters in the string are lowercase.
s = "python"
print(s.islower()) #Output True
s = "Python"
print(s.islower()) #Output False
#if only numbers the false if mix of num and lowercase letter then true
# isprintable() checks if all characters in a string are printable.
s = "Hello World!123"
print(s.isprintable()) #Output True
s = "Hello\nWorld"
print(s.isprintable()) #Output False
# Empty string is considered printable
# isspace() checks if all characters in a string are whitespace characters.
# Whitespace characters include: space ' ', tab \t, newline \n, carriage return \r, etc.
s = " "
print(s.isspace()) #Output True
s = " \t "
print(s.isspace()) #Output True
s = " hello "
print(s.isspace()) #Output False
# Empty string has no characters, so it’s not considered whitespace
# istitle() checks whether a string is in title case.
# A string is considered title case if each word starts with an uppercase letter and the remaining letters are lowercase.
s = "Hello World"
print(s.istitle()) #Output True
s = "hello World"
print(s.istitle()) #Output False
# isupper() checks whether all alphabetic characters in a string are uppercase.
s = "PYTHON"
print(s.isupper()) #Output True
s = "Python"
print(s.isupper()) #Output False
# Numbers with words do not affect the result
# swapcase() converts all lowercase letters to uppercase and all uppercase-
# letters to lowercase in a string.
s = "Hello World"
print(s.swapcase()) #Output hELLO wORLD
s = "python"
print(s.swapcase()) #Output PYTHON
# The title() method converts a string to title case:
# The first letter of each word becomes uppercase
# All other letters become lowercase
s = "pyTHon proGRAMMing"
print(s.title()) #Output Python Programming
# TO check if element present in string using (in) keyword
if "Har" in "Harry":
print("YES")
else:
print("NO")
# ===================
# String Formatting
# ===================
name = "Eddie"
#! f-string (best & modern)
print(f"Hello {name}") # Hello Eddie
#! format() method
print("Hello {}".format(name)) # Hello Eddie
letter = "Hey my name is {} and I am form {}"
country = "India"
name = "Jackal"
# print(letter.format(country, name)) #complicated way
print(f"Hello my name is {name} and I am form {country}") #Better way
print(f"Hello my name is {{name}} and I am form {{country}}") #To print as it is
price = 49.0999
txt = f"For only {price: .2f} dollars!"
print(txt)
num = f"{2 * 30}"
print(num) #So it prints "60" as text.
print(40*40) #Python calculates 40 × 40 = 1600 and prints the number.
# Old-style formatting
print("Hello %s" % name) # Hello Eddie
# Multi-line string
text = """This
is
multiline"""
print(text)
# Check if substring exists in string
print("py" in "python") # True
# Concatenate strings
a = "Hello"
b = "World"
print(a + b) # HelloWorld
# Repeat strings multiple times
print("Hi" * 3) # HiHiHi
# =====================
# DocStrings and PEP-8
# =====================
# A docstring is a description written inside triple quotes """ """ at the-
# start of a function or class to explain what it does.
# Written inside triple quotes.
# Must be at the top inside the function/class.
# Used for documentation.
# def add(a, b):
# """This function adds two numbers and returns the result."""
# return a + b
# help(add) # Output: add(a, b)
# # This function adds two numbers and returns the result.
# print(add(4,6))
def square(n):
'''Takes in a number n, returns the
square of n'''
print(n**2)
square(5)
print(square.__doc__) #Takes in a number n, returns the square of n
# PEP-8 (Python Enhancement Proposal 8)
# PEP 8 is a set of rules that tell you how to write clean, readable, and professional Python code.
# Think of it like grammar rules for Python coding.
# 🔥 What PEP 8 includes?
# It gives rules for things like:
# ✔ Naming
# variables_like_this
# functions_like_this()
# ClassesLikeThis
# ✔ Indentation
# Use 4 spaces for each indent.
# ✔ Line length
# Keep lines ≤ 79 characters.
# ✔ Spaces
# Add spaces around operators:
# a = 5 + 3
# ✔ Comments
# Use meaningful comments.
# Use docstrings for functions.
# ✔ Blank lines
# Add blank lines between functions to improve readability.
# 👍 Why is PEP 8 important?
# Because it:
# Makes your code clean
# Easy for others to read
# Looks professional
# Followed by almost all Python developers
# The Zen of Python
# The Zen of Python is a collection of guiding principles for writing Python code.
# It’s like Python’s philosophy on how code should look and behave—simple, readable, and elegant.
# On cmd type python then write import this
# >>> import this
# The Zen of Python, by Tim Peters
# Beautiful is better than ugly.
# Explicit is better than implicit.
# Simple is better than complex.
# Complex is better than complicated.
# Flat is better than nested.
# Sparse is better than dense.
# Readability counts.
# Special cases aren't special enough to break the rules.
# Although practicality beats purity.
# Errors should never pass silently.
# Unless explicitly silenced.
# In the face of ambiguity, refuse the temptation to guess.
# There should be one-- and preferably only one --obvious way to do it.
# Although that way may not be obvious at first unless you're Dutch.
# Now is better than never.
# Although never is often better than *right* now.
# If the implementation is hard to explain, it's a bad idea.
# If the implementation is easy to explain, it may be a good idea.
# Namespaces are one honking great idea -- let's do more of those!
# >>>
# ============
# Questions
# ============
#? Q1:
#? Write a program that takes a string from the user and prints the number of
#? spaces in the string.
#? Q2:
#? Ask the user for a string and print:
#? • All unique characters
#? • The count of unique characters
#? Q3:
#? Ask the user for a string and check whether it is a palindrome or not.
#? A is a string which is same when we read it forward & backward. Eg -
#? “madam”, “racecar” etc.
#? Q4:
#? Write a program to reverse words in a sentence.
#? Example: "I love Python" → "Python love I"
#? Q5:
#? Using Python, remove all spaces from a string without using replace().
#? Q6:
#? Write a program that takes a string from the user and prints the number of
#? spaces in the string.