0

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!

Mohammed
  • 1,364
  • 5
  • 16
  • 32

2 Answers2

0

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$'
>>>
Community
  • 1
  • 1
  • thank you for your help. Still I have one more question. How can I loop over characters of items in a list and perform operations on them. For example for item in lst: for char in lst[item]: if char == so and so: do this action – Mohammed Apr 28 '14 at 20:36
  • Please pardon me because I cannot format the code. I am just typing from my mobile device. – Mohammed Apr 28 '14 at 20:38
0

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$']
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76