Finding multiple characters in a string: python3 [duplicate] - python

This question already has answers here:
How to find char in string and get all the indexes?
(12 answers)
Closed 4 years ago.
I would like to find all the indexes of the letter 'a' in a string 'akacja'. However python always seems to return only the first index that it has found.
Any solutions?
Thanks for help.

You could use list comprehension since str.index() and str.find() will only return the first index:
s = 'akacja'
indexes = [i for i, c in enumerate(s) if c == 'a']
print(indexes)
# OUTPUT
# [0, 2, 5]

You could do this …
indexes = [i for i,c in enumerate('akacja') if c == 'a']
The above line uses list comprehension which is short hand for:
indexes = []
for i,c in enumerated('akacja'):
if c == 'a':
indexes.append(i)
You could also use regex like so:
import re
indexes = [f.start() for f in re.finditer('a', 'akacja')]

Related

How to replace each string in a list with some other string in python [duplicate]

This question already has answers here:
Finding and replacing elements in a list
(10 answers)
Replace values in list using Python [duplicate]
(7 answers)
Closed 2 years ago.
I'm making a hangman game, recently started python and looks like a good project I'd like to do, and so far its going great, I have a function that takes a string and puts it in a list like this:
Word: duck
List: ["d", "u", "c", "k"]
Now I want to replace the D U C K letters with "_"
I tried:
for char in List:
List.replace("d", "_")
This doesn't do anything also I dont want to do it for every single letter separately I would like something like this:
for char in List:
List.replace(char, "_")
I hope this is understandable
You can do that in two steps:
# Find the index of the string in your list
index = List.index(char)
# Replace
List[index] = '_'
The code above would replace the first occurrence only. To replace all you can either loop while the index is not -1 or use a comprehension:
List = ['_' if c == char else c for c in List]
or if you want to replace a specified set of letters:
chars = ['D', 'U', 'C', 'K']
List = ['_' if c in chars else c for c in List]
If all you want is a series of _ characters, then you might as well use this:
List = ['_'] * len(List)

why using x in list and change x's value did not work in Python [duplicate]

This question already has answers here:
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 4 years ago.
Suppose I have a list nums = [1,3,2,5,6] and I want to subtract each element's value by 1. Now I wrote codes like
for i in nums:
i -= 1
However, when I print nums its values did not change. I'm wondering why it doesn't work, and whether there is an elegant way in Python to do this. Thank you!
i is a local variable and does not reflect the actual objects in nums, only their values. The best way to do this is to use a list comprehension:
nums = [i - 1 for i in nums]
If you need to retain references to nums:
nums[:] = = [i - 1 for i in nums]
Demo:
>>> nums = [1, 2, 3]
>>> [i - 1 for i in nums]
[0, 1, 2]
The for loop sets i to successive values in the list, not references into the list. There are a couple ways to accomplish what you want:
nums = [i-1 for i in nums]
Is one way. If you need to keep the same list object you could do:
for ndx in xrange(len(nums)):
nums[ndx] -= 1

find index of values containing keyword in array python [duplicate]

This question already has answers here:
Finding the index of an item in a list
(43 answers)
Closed 4 years ago.
I want to find the index of values that contain a keyword in an array.
For example:
A = ['a1','b1','a324']
keyword = 'a'
I want to get [0,2], which is the index of a1, a324
I tried this list(filter(lambda x:'a' in x, A))
But get ['a1','a324'] rather than the index.
Use enumerate with a list-comprehension:
A = ['a1','b1','a324']
keyword = 'a'
print([i for i, x in enumerate(A) if keyword in x])
# [0, 2]
Simply write:
A = ['a1','b1','a324']
keyword = 'a'
indices = [i for i in range(len(A)) if keyword in A[i]]
print(indices)

in Python, How to join a list of tuples into one list? [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 9 years ago.
Following on my previous question How to group list items into tuple?
If I have a list of tuples, for example
a = [(1,3),(5,4)]
How can I unpack the tuples and reformat it into one single list
b = [1,3,5,4]
I think this also has to do with the iter function, but I really don't know how to do this. Please enlighten me.
b = [i for sub in a for i in sub]
That will do the trick.
In [11]: list(itertools.chain(*a))
Out[11]: [1, 3, 5, 4]
If you just need to iterate over 1, 3, 5, 4, you can get rid of the list() call.
Just iterate over the list a and unpack the tuples:
l = []
for x,y in a:
l.append(x)
l.append(y)
Another way:
a = [(1,3),(5,4)]
b = []
for i in a:
for j in i:
b.append(j)
print b
This will only handle the tuples inside the list (a) tho. You need to add if-else statements if you want to parse in loose variables too, like;
a = [(1,3),(5,4), 23, [21, 22], {'somevalue'}]
b = []
for i in a:
if type(i) == (tuple) or type(i) == (list) or type(i) == (set):
for j in i:
b.append(j)
else:
b.append(i)
print b
import itertools
b = [i for i in itertools.chain(*[(1,3),(5,4)])]

Find all the indexes of a number in a list [duplicate]

This question already has answers here:
How to find all occurrences of an element in a list
(18 answers)
Closed 10 years ago.
I have the following list:
lista = [1,2,3,5,0,5,6,0]
I know that print(lista.index(0)) will print the first index where it found the number i.e. 4
How do I get it to print the next index which should be 7 etc?
The classic way is to build a list of the indices:
eg:
>>> indices = [i for i, v in enumerate(a) if v == 0]
>>> print indices
[4, 7]
Of course - this can be turned into a generator expression instead. But in short - using enumerate is what you're after.

Categories