How to Index a Middle Character in a List in Python

How to return the middle character of a string in python?

Your code fails on edge cases, specifically when given the empty string, but I found during my tests that it works for strings like "asaba", "aaaa", and "abc" but throws the error when given "". The reason for this is because lastnum = enum[-1][0] + 1 will give an index that does not exist for the empty string. The way to fix this would be to add a condition at the beginning of your function that checks if it's an empty string, so like this:

if len(string) == 0:
return ""

Find middle of a list

Why would you use a list comprehension? A list comprehension only knows about any one member of a list at a time, so that would be an odd approach. Instead:

def findMiddle(input_list):
middle = float(len(input_list))/2
if middle % 2 != 0:
return input_list[int(middle - .5)]
else:
return (input_list[int(middle)], input_list[int(middle-1)])

This one should return the middle item in the list if it's an odd number list, or a tuple containing the middle two items if it's an even numbered list.

Edit:

Thinking some more about how one could do this with a list comprehension, just for fun. Came up with this:

[lis[i] for i in 
range((len(lis)/2) - (1 if float(len(lis)) % 2 == 0 else 0), len(lis)/2+1)]

read as:

"Return an array containing the ith digit(s) of array lis, where i is/are the members of a range, which starts at the length of lis, divided by 2, from which we then subtract either 1 if the length of the list is even, or 0 if it is odd, and which ends at the length of lis, divided by 2, to which we add 1."

The start/end of range correspond to the index(es) we want to extract from lis, keeping in mind which arguments are inclusive/exclusive from the range() function in python.

If you know it's going to be an odd length list every time, you can tack on a [0] to the end there to get the actual single value (instead of an array containing a single value), but if it can or will be an even length list, and you want to return an array containing the two middle values OR an array of the single value, leave as is. :)

How to split string in Python to take only middle characters?

You are going in the right direction.

Contrary to other answers, I feel regex is a bit of an overkill, apart from being slower and harder to understand and maintain.

Once you have the string x = '2020-05-27T11-59-06', you can do x.split('-') to get a list lst = ['2020', '05', '27T11', '59', '06'].

You can then access the last 2 elements of this list to get what you want easily: lst[-1], lst[-2].

Display the middle elements of a string

In Python, there are two kinds of division: integer division and float division.

    print(4 / 2)
---> 2.0
print(4 // 2)
---> 2

in Python 2, dividing one integer to an another integer,it comes an integer.
Since Python doesn't declare data types in advance, The interpreter automatically detects the type so you never know when you want to use integers and when you want to use a float.

Since floats lose precision, it's not advised to use them in integral calculations

To solve this problem, future Python modules included a new type of division called integer division given by the operator //

Now, / performs - float division, and
// performs - integer division.

Sort list based on character in middle of string

The key to sorting the list by the names stored in the strings is, to extract the age from the string. Once, you have defined a function which does that, you can use the key argument of the .sort method. Using regular expressions, extracting the age is simple. A solution could look as follows.

import re

pattern = re.compile(r'age:\s*(\d+)', re.IGNORECASE)

def extract_age(s):
return int(pattern.search(s).group(1))

list_names = ['Name: Mark - Age: 42 - Country: NL',
'Name: Katherine - Age: 23 - Country: NL',
'Name: Tom - Age: 31 - Country: NL']

list_names.sort(key=extract_age)
print(list_names)

How do I return the middle of a python array?

You're unnecessarily calling the pop() method on primary with [mid] when you should simply be indexing primary with mid. You should also use the // operator instead of / to obtain an integer value for the index. Since the index is 0-based, the mid point should be (length - 1) // 2 instead:

primary = []
length = 0
i = ("MORE")
while i != "NOMORE":
i = str(input("?"))
print(i)
if i == "NOMORE":
break
primary.append(i)
length = length + 1
mid = (length - 1) // 2

print(primary[0]," , ", primary[-1]," , ",primary[mid])

How to slice middle element from list

You cannot emulate pop with a single slice, since a slice only gives you a single start and end index.

You can, however, use two slices:

>>> a = [3, 4, 54, 8, 96, 2]
>>> a[:2] + a[3:]
[3, 4, 8, 96, 2]

You could wrap this into a function:

>>> def cutout(seq, idx):
"""
Remove element at `idx` from `seq`.
TODO: error checks.
"""
return seq[:idx] + seq[idx + 1:]

>>> cutout([3, 4, 54, 8, 96, 2], 2)
[3, 4, 8, 96, 2]

However, pop will be faster. The list pop function is defined in listobject.c.



Related Topics



Leave a reply



Submit