1

I have a list in python which is produced from a number of functions. It is produced like this:

['01', '1.0', '[0.2]']

I would like to strip all of the unnecessary characters after it is produced.

Ideal output:

['01', '1.0', '0.2']

I basically need to remove the [ and ] from the final string in the list.

Update:

list_test = ['01', '1.0', '[0.2]']
[i.strip('[]') if type(i) == str else str(i) for i in list_test]
print(list_test)

This doesn't work as both with and without produce the same result:

['01', '1.0', '[0.2]']

The required result is:

['01', '1.0', '0.2']

Provided solution:

l = ['01', '1.0', '[0.2]']
[i.strip('[0.2]') if type(i) == str else str(i) for i in l]
print(l)

output:

['01', '1.0', '0.2']

Process finished with exit code 0
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
JAM
  • 125
  • 1
  • 2
  • 12
  • 3
    show us your code currently – depperm Jan 05 '17 at 20:35
  • That is my code. I have been given the top list and need to produce the bottom output. – JAM Jan 05 '17 at 20:37
  • 9
    That is not code, that is input and output, what have you tried yourself to turn the input into the output ? – MooingRawr Jan 05 '17 at 20:38
  • 1
    I understand you get through strange circunstances a "mixed bag" of values and you want to normalize them, right? Why is the first item `01` and not `1`? – hansaplast Jan 05 '17 at 20:40
  • I believe its a product code rather than an int or float – JAM Jan 05 '17 at 20:41
  • almost duplicate of [Print list without brackets in a single row](http://stackoverflow.com/questions/11178061/print-list-without-brackets-in-a-single-row) but I have no Idea what logic you are expecting to apply to a sublist. – Tadhg McDonald-Jensen Jan 05 '17 at 20:54
  • Is there only ever 1 item in the string-list? – roganjosh Jan 05 '17 at 21:39
  • @JAM The answer you had earlier were based on the input list and the result you initially mentioned with the question. If you will change these values, the current answers will become invalid. It will be confusing for other people looking at the post in future. Please be careful when you ask any question – Moinuddin Quadri Jan 05 '17 at 21:57
  • Apologies, as I said I'm new to this and didn't realise it was wrong in my original question. I agree it can be confusing. Its definitely something I've learnt from, thank you. – JAM Jan 05 '17 at 21:58
  • @JAM don't be discouraged. Stackoverflow is sometimes not really helpful for newcomers. It's rough at the start but worth the trouble. You solved it by being active in the edits and comments, that helps. – hansaplast Jan 05 '17 at 22:07
  • @hansaplast Thanks! You're extremely helpful! It's nice to come across people who genuinely want to help! – JAM Jan 05 '17 at 22:10
  • 1
    @JAM from the way you ask and the sort of problem you face you seem like someone who is new to programming and got the task of taking over someones else's code. If this assumption is right: This is a tremendous opportunity and kudos for accepting it. I recommend diving into python ([here](https://www.quora.com/How-should-I-start-learning-Python-1/answer/Paul-DeVos) are some recommendations or do the [python lectures](https://www.codeschool.com/learn/python) at codeschool – hansaplast Jan 06 '17 at 21:40
  • Thanks for all your help @hansaplast – JAM Jan 07 '17 at 12:47

3 Answers3

18

If you just need to remove an optional [ and ] around a string, this one-liner should do the trick:

l = [i.strip('[]') for i in l]

with your example

>>> l = ['01', '1.0', '[0.2]']
>>> [i.strip('[]') for i in l]
['01', '1.0', '0.2']

What it does: it iterates over all strings of the list and removes any [ and ] if they are at the beginning or end of the string. It also would make ]0.2[ into 0.2.

Update:

I get AttributeError: 'int' object has no attribute 'strip'

In this case you have an int in your input array, this one liner should do the trick:

l = [i.strip('[]') if type(i) == str else str(i) for i in l]

With an example with an int:

>>> l = ['01', '1.0', '[0.2]', 2]
>>> [i.strip('[]') if type(i) == str else str(i) for i in l]
['01', '1.0', '0.2', '2']

what it does is that it

  • only strips away [ and ] from strings
  • converts everything that is not a string into a string
hansaplast
  • 11,007
  • 2
  • 61
  • 75
  • 1
    @JAM Confirmed that `[i.strip('[]') if type(i) == str else str(i) for i in l]` also gives expected result in Python 2 – roganjosh Jan 05 '17 at 22:48
2

If you are ok with using regex, you may fetch the numbers from the string as:

>>> import re
>>> my_list = ['01', 1.0, [0.2]]
>>> my_nums = re.findall('\d+\.?\d*', repr(my_list))
#      ^                                 ^ convert `list` to `str` representation
#      ^ value of `my_nums` > ['01', '1.0', '0.2']

>>> ', '.join(my_nums)
'01, 1.0, 0.2'   # <--- Desired result

Else, may convert the list to str and remove the content from the string based on the list of items you want to remove. For example:

my_list = ['01', 1.0, [0.2]]
remove_content = ["'", "[", "]"] # Content you want to be removed from `str`

my_str = repr(my_list)  # convert list to `str`

for content in remove_content:
    my_str = my_str.replace(content, '')

Final value hold by my_str will be:

>>> my_str
'01, 1.0, 0.2'
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • This worked great. How would I get it to keep them as separate items i.e: '01', '1.0', '0.2' – JAM Jan 05 '17 at 21:09
  • @JAM In first approach using *regex*, `my_nums` holds the value you desire. In the second approach, you need to split the `my_str` as `my_str .split(', ')` – Moinuddin Quadri Jan 05 '17 at 21:18
  • I have edited the question to make it more clear. I need the three items as seperate items in the list. Each one is a str but I need to remove the [ and ] from the last item. – JAM Jan 05 '17 at 21:32
  • Three separate string are needed to be wrapped in some data structure i.e. either a `list` or `tuple`. Either it will be a single string or list/tuple of strings – Moinuddin Quadri Jan 05 '17 at 21:37
  • Sorry, I've edited again. I'm very new to this. I just need the [ and ] removing from the third item but I don't seem to be able to do this. – JAM Jan 05 '17 at 21:38
  • Do you want to just **print** the result as `'01', '1.0', '0.2'`? – Moinuddin Quadri Jan 05 '17 at 21:39
  • The results will be used to write to a CSV so I need the list to have 3 items so I can use `for item in list: add to csv` – JAM Jan 05 '17 at 21:40
0

You don't need regex, something this simple will work.

(str(['01', 1.0, [0.2]])
 .replace('[','')
 .replace(']','')
 .replace("'",'')
 .replace('"',''))

Or, if you have many characters you consider unnecessary,

chars2remove = '''[]'"'''
s = str(['01', 1.0, [0.2]])
for char in chars2remove:
    s = s.replace(char, '')
BallpointBen
  • 9,406
  • 1
  • 32
  • 62