Skip to content

Commit d4ceefa

Browse files
Create Extracting_Middle_Chars.py
1 parent 925e21c commit d4ceefa

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Extracting middle characters from a string can achieved any number of ways:
2+
3+
# an ugly way to do it:
4+
5+
def get_middle(s):
6+
i = 0
7+
for x in s:
8+
i += 1
9+
print(i)
10+
middle = (i/2)
11+
print(middle)
12+
if i % 2 == 0:
13+
return "".join(s[middle-1]+s[middle])
14+
else:
15+
return s[middle]
16+
17+
# This can be cleverly abbreviated as follows;
18+
19+
def get_middle(s):
20+
return s[(len(s)-1)/2:len(s)/2+1]
21+
22+
# or one can use divmod:
23+
24+
def get_middle(s):
25+
index, odd = divmod(len(s), 2)
26+
return s[index] if odd else s[index - 1:index + 1]
27+
28+
# or:
29+
30+
def get_middle(s):
31+
strLen = len(s)
32+
if(strLen%2==0):#even
33+
return s[strLen/2-1:strLen/2+1]
34+
else:#odd
35+
return s[strLen/2]

0 commit comments

Comments
 (0)