-1

i am running this code :

list = ['  843Mi ', '  843Mi ', '  843Mi ', '  843Mi ', '  843Mi ', '  843Mi ']
list = [s.replace('Mi','')for s in list]
print(list)
list = [s.replace(' ','')for s in list]
print(list)

But getting output like this

['843', '843', '843', '843', '843', '843']

but i want output like this :

[843,843,843,843,843,843]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 2
    you need to convert the string into an integer using `int`. – Vishal Singh Mar 05 '21 at 14:30
  • You can "remove quotes" by converting to int, but Python will still put the spaces between the items. If you want exactly the output you show, you'll have to build your own string not rely on the `__repr__`esentation of the list. – jonrsharpe Mar 05 '21 at 14:31
  • Does this answer your question? [How to convert strings into integers in Python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python) – Jason Rebelo Neves Mar 05 '21 at 14:32
  • 2
    Note: You shouldn't use built in **list function** as variable. – Spiros Gkogkas Mar 05 '21 at 14:52
  • If you simply want integer than see the all the comments/answer. Note that spacing after the comma is not possible (your output suggests you want that removed). This is PEP8 style. – astrochun Mar 05 '21 at 15:00
  • Does this answer your question? [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int) – Karl Knechtel May 18 '23 at 23:59
  • It would be better to ask a question *about the part of the problem that is actually causing a problem*, rather than phrasing it about the entire task. – Karl Knechtel May 19 '23 at 00:00

2 Answers2

1

With your example you could do something like this after replacing the characters:

lst = [int(string) for string in lst]
Spiros Gkogkas
  • 432
  • 5
  • 11
1
  1. You should not use list as a variable name.
  2. The operations you are doing can be clubbed together.
  3. int() is used for converting the valid string to a number.

Please see below:

>>> raw_data = ['  843Mi ', '  843Mi ', '  843Mi ', '  843Mi ', '  843Mi ', '  843Mi ']
>>> processed_data = [int(x.strip().strip('Mi')) for x in a]
>>> processed_data
[843, 843, 843, 843, 843, 843]
>>> 


lllrnr101
  • 2,288
  • 2
  • 4
  • 15