-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMastering Python Strings notes
More file actions
164 lines (96 loc) · 1.66 KB
/
Mastering Python Strings notes
File metadata and controls
164 lines (96 loc) · 1.66 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
String in Python
A string is a sequence of characters enclosed in quotes.
str1 = "Tulasi"
1) Indexing
Access individual characters using index numbers.
Forward Indexing
Starts from 0
T u l a s i
0 1 2 3 4 5
Example:
str1[3]
Output:
'a'
2) Negative Indexing
Starts from -1
T u l a s i
-6 -5 -4 -3 -2 -1
Example:
str1[-1]
Output:
'i'
3) Length of String
Use len() to find total characters.
len(str1)
Output:
6
String Functions
find()
Returns index if character exists, otherwise returns -1
str1.find("a")
Output:
3
Character not present:
str1.find("k")
Output:
-1
split()
Breaks string into list of words.
text = "hello tulasi"
text.split()
Output:
['hello', 'tulasi']
Used heavily in text processing/NLP.
replace()
Replaces one word with another.
text.replace("tulasi","python")
Output:
'hello python'
Original string remains same unless reassigned.
count()
Counts occurrences of character.
str2 = "Tulasi kumar sahu"
str2.count("a")
Case Sensitive
str2.count("T")
str2.count("t")
Both are treated differently.
Case Conversion Functions
lower()
Converts all characters to lowercase
str2.lower()
upper()
Converts all characters to uppercase
str2.upper()
swapcase()
Lower → Upper
Upper → Lower
str2.swapcase()
title()
Capitalizes first letter of every word
str3.title()
capitalize()
Capitalizes only first letter of full sentence
str3.capitalize()
String Slicing
Syntax:
string[start:end:step]
Normal slicing
str1[0:3]
Output:
'Tul'
End index is not included.
Skip characters
str1[0:6:2]
Output:
'Tls'
Shortcut:
str1[::2]
Reverse String
str1[::-1]
Output:
'isaluT'
Partial Reverse
str1[:1:-1]
Output:
'isa'