-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_string_functions.py
More file actions
385 lines (323 loc) · 16.2 KB
/
Copy path06_string_functions.py
File metadata and controls
385 lines (323 loc) · 16.2 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
#======================================================================================
# STRING FUNCTIONS
#======================================================================================
#======================================================================================
# 1) types
#--------------------------------------------------------------------------------------
# a) type() ---built-in function / output:type (like str, int, float, bool)
# b) str() ---built-in function / output:string
#======================================================================================
#--------------------------------------------------------------------------------------
# a) type(value)--returns the data type of a value.
#--------------------------------------------------------------------------------------
name = "Bob"
print(type(name))
age = 25
print(type(age))
# print("Your age is:" + age) #can't combine a string with an integer using + operator.
#--------------------------------------------------------------------------------------
# b) str(value)--converts any value into string value.
#--------------------------------------------------------------------------------------
# Here the age is converted to str only in this print statement.
print("Your age is:"+str(age))
print(type(age)) # we can also check that the data type is not changed.
# This is how we convert the int data type to str using str function.
age = str(age)
print(type(age)) # We can also check that the data type is changed.
# Python is flexible with Data Types.
#======================================================================================
# 2) Math
#--------------------------------------------------------------------------------------
# a) len() ---built-in function /output:int
# b) count() ---str method /output:int
#======================================================================================
#--------------------------------------------------------------------------------------
# a) len(value)--returns the no of characters in string, it counts everything even spaces.
#--------------------------------------------------------------------------------------
password = "2580mun "
print(len(password))
#--------------------------------------------------------------------------------------
# b) count(substring)--returns how often a word appears in the string.
#--------------------------------------------------------------------------------------
text = """
Python is easy to learn.
Python is powerful.
Many people love python.
"""
print(text.count("Python")) # the output is 2 because the Python is case-sensitive.
#======================================================================================
# 3) Transformations
#--------------------------------------------------------------------------------------
# a) replace() ----str method
# b) concatenation ex:'H' + 'i' ----operator /output:string
# c) f_string(f{}) ----operator
# d) split() ----str method /output:list of strings
# e) string repetition ex:'ha'*2 ----operator /output:string
# f) indexing ex:'cat'[0] ----operator /output:string
# g) slicing ex:'cat'[1:3] ----operator /output:string
#======================================================================================
#--------------------------------------------------------------------------------------
# a) replace(old, new) --swaps part of the text with something new.
#--------------------------------------------------------------------------------------
phone = "630-1701-800"
print(phone.replace("-", ""))
ph = "+49 (176) 123-4567"
print(ph.replace("+", "").replace(" ",
"").replace("(", "").replace(")", "").replace("-", ""))
#--------------------------------------------------------------------------------------
# b) concatenations --Joins two strings into one.
#--------------------------------------------------------------------------------------
first_name = "Bob"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name)
folder = "C:/Users/Smith/"
file = "reports.csv"
full_file_path = folder + file
print(full_file_path)
#--------------------------------------------------------------------------------------
# c) f-string(f{})--"f" stands for "formatted",it lets you easily put variables and
# expressions directly inside string value.
#--------------------------------------------------------------------------------------
name = "Bob"
age = "25"
is_student = False
print("My Name is", name, "I am", age,
"year Old and Student status is", is_student) # Hard to read
print("My Name is " + name, "I am "+str(age) +
" years Old and Student status is " + str(is_student)) # Hard to read
#--------------------------------------------------------------------------------------
# f-string:shorter, cleaner, easier to read!.
# variables in f-string.
#--------------------------------------------------------------------------------------
print(f"My Name is {name} I am {age} years Old and Student status is {is_student}")
print(f"2 + 3 = {2+3}") # expressions in f-string.
# printing curly braces using double {{}} curly braces.
print(f"Hello {{Welcome to Python}}")
#--------------------------------------------------------------------------------------
# d) split(separator)-- breaks a string into smaller parts.
#--------------------------------------------------------------------------------------
csv_file = "123,Max,USA, 1970-10-05,M"
print(csv_file.split(","))
stamp = "2025-01-19"
print(stamp.split("-"))
#--------------------------------------------------------------------------------------
# e) string * number ---repeats the string multiple times.
#--------------------------------------------------------------------------------------
print("Ha "*3)
print("**"*10)
#--------------------------------------------------------------------------------------
# In Python, indexing and slicing are the ways to access
# parts of sequence such as strings, lists, tuple, etc.
#--------------------------------------------------------------------------------------
# f) Indexing
#--------------------------------------------------------------------------------------
# indexing means accessing one single element from a sequence using its
# position number(index)
#--------------------------------------------------------------------------------------
# imp rule **Python index starts from 0
# **Negative indexing starts from -1 (last element)
#--------------------------------------------------------------------------------------
text = "Python"
#------------------------------------------------
# Value | #positive-index | #Negative-index |
#------------------------------------------------
# p | 0 | -6 |
# y | 1 | -5 |
# t | 2 | -4 |
# h | 3 | -3 |
# o | 4 | -2 |
# n | 5 | -1 |
#------------------------------------------------
# extracting the first character using +ve and -ve index number
print(text[0])
print(text[-6])
# extracting the last character using +ve and -ve index number
print(text[5])
print(text[-1])
# extract h
print(text[3])
#--------------------------------------------------------------------------------------
# g) Slicing
#--------------------------------------------------------------------------------------
# slicing means extracting multiple elements (a portion) from a sequence.
# Syntax:- sequence[start:end:step].
# start:starting index (include).
# end:ending index (excluded).
# step:gap between elements (optional).
#--------------------------------------------------------------------------------------
date = "2025-01-19"
# extract the year
print(date[0:4])
# if you leave the start index empty, python starts form index 0
print(date[:4])
# extract the month
print(date[5:7])
# extract the day
print(date[8:])
print(date[-2:])
#--------------------------------------------------------------------------------------
# when to use positive or negative index.
#--------------------------------------------------------------------------------------
# Use Positive index if you want to extract part from the left side (start) of a string.
# Use Negative index if you want to extract part from the right side (end) of a string.
#--------------------------------------------------------------------------------------
#======================================================================================
# 4 Cleaning
#--------------------------------------------------------------------------------------
# ----------------------------------------------
# Clean WhiteSpaces
# ----------------------------------------------
# a) lstrip() ---str method /output:string
# b) rstrip() ---str method /output:string
# c) strip() ---str method /output:string
# ----------------------------------------------
# Clean Cases
# ----------------------------------------------
# d) lower() ---str method /output:string
# e) upper() ---str method /output:string
#======================================================================================
#--------------------------------------------------------------------------------------
# Whitespace Cleanup
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
# a) lstrip()--removes spaces from the left side of a string.
#--------------------------------------------------------------------------------------
text = " Engineering".lstrip()
print(text, len(text))
#--------------------------------------------------------------------------------------
# b) rstrip()--removes spaces from the right side of a string
#--------------------------------------------------------------------------------------
text = "Engineering ".rstrip()
print(text, len(text))
#--------------------------------------------------------------------------------------
# c) strip()--removes spaces from both ends
#--------------------------------------------------------------------------------------
text = " Engineering ".strip()
print(text, len(text))
# only removes spaces at the start or end, not in the middle
text = "Data Engineering".strip()
print(text, len(text))
# it removes any characters you want from the start and end - not just spaces
text = "###ABC###".strip("#")
print(text, len(text))
# How to check the quality of the data
text = " Engineering ".strip()
print(len(text))
print(len(text.strip()))
no_of_spaces = len(text) - len(text.strip())
is_clean = len(text) == len(text.strip())
print(f"No of Spaces: {no_of_spaces}")
print(f"Is my Data Clean?:{is_clean}")
# Best Practice-- Trim Spaces form User input.
#--------------------------------------------------------------------------------------
# Cases Conversions
#--------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------
# d)lower()--makes all letters lowercase.
#--------------------------------------------------------------------------------------
text = "python PROGRAMMING"
print(text.lower())
#--------------------------------------------------------------------------------------
# e)upper()--makes all letters uppercase.
#--------------------------------------------------------------------------------------
print(text.upper())
search = "Email"
data = "email"
print(search == data)
# use case:- Clean Data for Matching
# Lowercase all text to prevent case-based mismatches during search or comparison.
search = "Email".lower()
data = "eMaiL".lower()
print(search == data) # True
search = " Email".lower()
data = "eMail ".lower()
print(search == data) # False
# Best Practice - Clean before search
# Always trim spaces and lowercase your data and search them before matching.
search = " Email".lower().strip()
data = "eMail ".lower().strip()
print(search == data)
#--------------------------------------------------------------------------------------
# Python Challenge
# expected out put: name:maria | role: data engineer | age: 27.
#--------------------------------------------------------------------------------------
s = "968-Maria ( D@t@ Engineer );; 27y"
clean = s.replace("968-", "").replace("@", "a").replace("(","").replace(")", "").replace(";", "").replace("y", "")
print(clean)
parts = clean.split()
print(parts)
name = parts[0].lower()
role = parts[1].lower() + " "+parts[2].lower()
age = parts[3]
print(f"name: {name} | role: {role} | age: {age}")
#======================================================================================
# 5 Search
#--------------------------------------------------------------------------------------
# a) startswith() ---str method /output:boolean
# b) endswith() ---str method /output:boolean
# c) 'a' in 'cat' ---operator /output:boolean
# d)find() ---str method /output:number
#======================================================================================
ph = "+91-630-1701-800"
#--------------------------------------------------------------------------------------
# a) startswith(substring)--checks if the string begins with a specific word.
#--------------------------------------------------------------------------------------
print(ph.startswith("630"))
print(ph.startswith("+91"))
#--------------------------------------------------------------------------------------
# b) endswith(substring)--checks if the string ends with a specific word.
#--------------------------------------------------------------------------------------
file = "report.csv"
print(file.endswith("rst"))
print(file.endswith(".csv"))
#--------------------------------------------------------------------------------------
# c) 'substring' in 'sting' -- checks if a word exists in the string.
#--------------------------------------------------------------------------------------
email = "BobSmith@gmail.com"
print("j" in email)
print("@" in email)
#--------------------------------------------------------------------------------------
# d)find(substring)--returns the starting position of a word in the string.
#--------------------------------------------------------------------------------------
text = "python programming"
print(text.find("program"))
phone1 = "+48-176-12345"
phone2 = "48-654-16548"
phone3 = "0048-654-16548"
# Extract only phone number without country code.
# Hardcoding the start position doesn't work when the country code length changes.
print(phone1[4:])
print(phone2[3:])
print(phone3[5:])
# Extracting only phone numbers with out country code by using find.
# print(phone1.find("-"))
# print(phone2.find("-"))
# print(phone3.find("-"))
print(phone1[phone1.find("-")+1:])
print(phone2[phone2.find("-")+1:])
print(phone3[phone3.find("-")+1:])
# find() is great when combined with other methods to add dynamics
#======================================================================================
# 6) Validation
#--------------------------------------------------------------------------------------
# a) isalpha() ---str method /output:boolean
# b) isnumeric() ---str method /output:boolean
#======================================================================================
#--------------------------------------------------------------------------------------
# a) isalpha()--checks if the string has only letters.
#--------------------------------------------------------------------------------------
country = "USA"
print(country.isalpha())
country = "USA1"
print(country.isalpha())
#--------------------------------------------------------------------------------------
# b) isnumeric()--checks if the string has only numbers.
#--------------------------------------------------------------------------------------
phone = "0987612345"
print(phone.isnumeric())
# . and - considered as special character that's why it is showing false in output
phone = "123-456-789"
print(phone.isnumeric())
price = "4.50"
print(price.isnumeric())