1

Well-experienced in C++, but new-ish to Python: I'd like to pull out the 2nd character in each element of the following list named input to a new list named output.

input = ['hail','2198','1721','1925']

output = ['a', '1', '7', '9']

Am I missing a simple operator that does this? Thanks

king2
  • 13
  • 2

4 Answers4

1

That's a list comprehension:

>>> input_ = ['hail','2198','1721','1925']
>>> [s[1] for s in input_]
['a', '1', '7', '9']

Note that input is the name of a built-in function in Python, so you should avoid to use that name for a local variable.

Graham
  • 7,431
  • 18
  • 59
  • 84
wim
  • 338,267
  • 99
  • 616
  • 750
1

Welcome to programming in Python :) .

The syntax for getting a character out of the string s is s[i] where i starts with 0 and goes up to n-1 where n is the length of the string.

In Python it is possible to create a list of elements using a syntax that explains itself when reading it. item[1] means in this context the second character/element in the string got from input because Python considers in this context a string to be a list of characters.

The right keywords to search the Internet for details will be "Python list comprehension" and "Python list slice".

output = [item[1] for item in input_] (see note in the other answer about 'input')

Compared to C++ Python will make coding a pleasure. You have just to write what you mean it has to be that way and it probably will be that way in Python - that is how I came from C++ to Python myself.

Claudio
  • 7,474
  • 3
  • 18
  • 48
  • super, easier but also a different metaphor--if you have thoughts on my comment below, thanks – king2 Apr 29 '17 at 04:42
1

This is for the character after '2'.

input_ = ['hail','2198','1721','1925']
result_list = []
for element in input_:
    character = '2' # in this case
    index_of_character = element.find(character)
    if index_of_character != -1 and index_of_character != len(element) -1:
        # -1 if character is not found in the string no need to append element after that
        # character should not be the last in the string otherwise index out of bound will occur
        result_list.append(element[index_of_character + 1])

print (result_list)

PS: This method only gives character only after first occurrence of two if there are multiple '2' in the string. You have to tweak this method

Yaman Jain
  • 1,254
  • 11
  • 16
0

You can solve it in one line using list-comprehension. You can select the second index element using input[i][1] at some index i.

>>>input = ['hail','2198','1721','1925'] 
>>>[x[1] for x in input]
['a', '1', '7', '9']

[x[1] for x in input] will create a list of elements where each element will be x[1].

Charul
  • 450
  • 5
  • 18