We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 925e21c commit d4ceefaCopy full SHA for d4ceefa
More Complex Functions/Extracting_Middle_Chars.py
@@ -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
20
+ return s[(len(s)-1)/2:len(s)/2+1]
21
22
+# or one can use divmod:
23
24
25
+ index, odd = divmod(len(s), 2)
26
+ return s[index] if odd else s[index - 1:index + 1]
27
28
+# or:
29
30
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