I have a list looking as follows
lst = ['.ab.cd.ef.gh.', '.ij.kl.mn.op.']
In each item, I want to replace item[0] with a * and item[-1] with a $.
I tried to use:
[item.eplace(item[0], '*') for item in lst]
but the result is that all . get replaced with * irrespective of position.
Appreciating your help!
This will work:
>>> lst = ['.ab.cd.ef.gh.', '.ij.kl.mn.op.']
>>> ['*' + item[1:-1] + '$' for item in lst]
['*ab.cd.ef.gh$', '*ij.kl.mn.op$']
>>>
item[1:-1], which uses Explain Python's slice notation, will get every character in item except for the first and the last:
>>> 'abcde'[1:-1]
'bcd'
>>> '*' + 'abcde'[1:-1] + '$' # Add the characters we want on each end
'*bcd$'
>>>
Use this code:
lst = ['.ab.cd.ef.gh.', '.ij.kl.mn.op.']
for k in range(0, len(lst)):
item = lst[k]
lst[k] = '*'+item[1:-1]+'$'
print lst
This loops over every item with a for loop and range(), and assigns lst[k] to item. Then it uses item[1:-1] to get the string excluding the first and last characters. Then we use string concatenation to add an asterisk to the beginning, and a dollar sign to the end. This runs as:
>>> lst = ['.ab.cd.ef.gh.', '.ij.kl.mn.op.']
>>> for k in range(0, len(lst)):
... item = lst[k]
... lst[k] = '*'+item[1:-1]+'$'
...
>>> print lst
['*ab.cd.ef.gh$', '*ij.kl.mn.op$']
>>>
Related
I know that my_str[1::3] gets me every 2nd character in chunks of 3, but what if I want to get every 2nd and 3rd character? Is there a neat way to do that with slicing, or do I need some other method like a list comprehension plus a join:
new_str = ''.join([s[i * 3 + 1: i * 3 + 3] for i in range(len(s) // 3)])
I think using a list comprehension with enumerate would be the cleanest.
>>> "".join(c if i % 3 in (1,2) else "" for (i, c) in enumerate("peasoup booze scaffold john"))
'eaou boz safol jhn'
Instead of getting only 2nd and 3rd characters, why not filter out the 1st items?
Something like this:
>>> str = '123456789'
>>> tmp = list(str)
>>> del tmp[::3]
>>> new_str = ''.join(tmp)
>>> new_str
'235689'
Let's say I have the following list of strings:
list = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03']
I want to change the 11th character of each string, meaning the 2nd '.', to a '-'.
I've tried:
list = [n[:10] + '-' + n[11:] for n in list]
However this gives me the error:
TypeError: 'float' object is not subscriptable
The problem is that you have a float somewhere in your list. You could use a for loop using enumerate and str to solve it:
lst = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03']
for index, item in enumerate(lst):
item = str(item)
lst[index] = item[0:10] + "-" + item[11:]
Or, as a list comprehension:
new_lst = [item[0:10] + "-" + item[11:]
for x in lst
for item in [str(x)]]
Also, avoid calling your variables like builtin-objects (list, dict and the like).
>>> a = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03']
>>> a = [n[:10] + '-' + n[11:] for n in a]
>>> a
['ABC.010120-01', 'ABC.010220-02', 'ABC.010220-03']
Note that list, as str, set and some others are word reserved for python3.
What you're doing it's like change the base of an int, for example.
The issue is that there are nan float values in the list. I found that following this solution linked here worked to remove the nan's from my list as so:
lst = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03', nan]
lst = [x for x in lst if x == x]
Executing that beforehand allows this line to function without error:
lst = [n[:10] + '-' + n[11:] for n in last]
I am creating a list of all versions of a string that can be made by deleting only one character using a comprehension. I am able to remove each character but not able to keep the other characters.
wrd = 'superstar'
list2 = [(wrd[:1-1] + wrd[:i+1]) for i in range(len(wrd))]
print(list2)
Your list slicing is a bit off. To remove a single character from a position in a string, use the form string[:index] + string[index + 1:] instead of string[:index - 1] + string[:index + 1]:
>>> word = 'superstar'
>>> words = [word[:i] + word[i + 1:] for i in range(len(word))]
>>> words
['uperstar', 'sperstar', 'suerstar', 'suprstar', 'supestar', 'supertar', 'supersar', 'superstr', 'supersta']
>>>
>>> from itertools import combinations
>>> wrd = 'superstar'
>>> [''.join(comb) for comb in combinations(wrd, len(wrd) - 1)]
['supersta', 'superstr', 'supersar', 'supertar', 'supestar', 'suprstar', 'suerstar', 'sperstar', 'uperstar']
Here's how to slice the 'wrd' superstar in a list comprehension:
wrd = 'superstar'
to remove each letter, you need to add the first part of the string to the second part that is leftover when you remove that character:
the first part of 'wrd' is everything up to i (your question has :1-1).
wrd[:i]
the second part of 'wrd' is everything from i+1 and onward to the end.
wrd[i+1:]
results:
list2 = [wrd[:i]+wrd[i+1:] for i in range(len(wrd))]
print(list2)
['uperstar', 'sperstar', 'suerstar', 'suprstar', 'supestar', 'supertar', 'supersar', 'superstr', 'supersta']
to delete more letters (like 2) at once in sequence, simply add to i in 'wrd':
list3 = [wrd[:i]+wrd[i+2:] for i in range(len(wrd))]
print(list3)
['perstar', 'serstar', 'surstar', 'supstar', 'supetar', 'superar', 'supersr', 'superst', 'supersta']
I'm trying to prepend zeros to each number in a list if it isn't a the necessary number of digits.
lst = ['1234','2345']
for x in lst:
while len(x) < 5:
x = '0' + x
print(lst)
Ideally this would print ['012345', '02345']
You can use zfill:
Pad a numeric string s on the left with zero digits until the given
width is reached
lst = ['1234','2345']
[s.zfill(5) for s in lst]
# ['01234', '02345']
Or use format method with padding and alignment:
["{:0>5}".format(s) for s in lst]
# ['01234', '02345']
You code doesn't do the job because strings in python are immutable, see this for more info Why doesn't calling a Python string method do anything unless you assign its output?
You could you enumerate in this case like this:
lst = ['1234','2345', "23456"]
for i, l in enumerate(lst):
if len(l) < 5:
lst[i] = '0' + l
print(lst)
['01234', '02345', '23456']
You could use a list comprehension like this:
>>> ['0' * (5-len(x)) + x for x in lst]
['01234', '02345']
Or a list + map try:
>>> list(map(lambda x: '0' * (5-len(x)) + x, lst))
['01234', '02345']
Ultimately, it was a combination of the answers that did the job.
lst = ['1234','2345']
newlst = []
for i in lst:
i = i.zfill(5)
newlst.append(i)
print(newlst)
I apologize if my example wasn't clear. Thank you to all who offered answers!
You can do this:
>>> lst = ['1234','2345']
>>> lst = ['0' * (5 - len(i)) + i for i in lst]
>>> print(lst)
['01234', '02345']
I am new to python and I'm wondering, how I would go about removing items from a list. Say I have the list:
a=[(102,12,0),(123,12,0),(124,12,1)]
I would like to remove the items that have a 0 at the end, so my list would end up like:
a = [(124,12,1)]
here:
a = [i for i in a if i[-1] != 0] #list comprehension (1 line) method.
"normal" way to do without list comprehension when the parent list is also destination list.
tmp = []
for i in a:
if i[-1] != 0:
tmp.append(i)
a = tmp
in action:
>>> a=[(102,12,0),(123,12,0),(124,12,1)]
>>> a = [i for i in a if i[-1] != 0]
>>> a
[(124, 12, 1)]
>>>
You can use list comprehensions
val[-1] would give you tuples with 0 at the end, assuming val is the variable used while iterating.
So, your code would be something like this:
a = [val for val in a if val[-1]]
Not as awesome as a one liner list comprehension but still do the trick :).
b = tuple
for tple in a:
b = b + tple
result = tuple
for val in set(b):
if val % 10 != 0:
result = result + (val,)