How to Remove a Single Quotes from a List

Remove single quote from list in Python

Treat the text as a row from a CSV formatted file:

import csv
import StringIO

result = '"testing","0.8841","642000.0","80.014521","-60.940653","4522126666","1500854400","","1500842014000","name","80.014521","-60.996532","sampledevice","3","name"'
print next(csv.reader(StringIO.StringIO(result)))

Giving you:

['testing', '0.8841', '642000.0', '80.014521', '-60.940653', '4522126666', '1500854400', '', '1500842014000', 'name', '80.014521', '-60.996532', 'sampledevice', '3', 'name']

Python's StringIO() function allows the text to be treated like a file allowing it to be passed to Python's CSV parser which is designed for parsing CSV files in this format. It can then correctly parse the text and return a list of items.


The returned data could then be further processed if needed to convert the text into numbers, i.e. integers or floats as appropriate. For example:

import csv
import StringIO

def convert(text):
try:
return int(text)
except ValueError:
pass

try:
return float(text)
except ValueError:
return text


result = '"testing","0.8841","642000.0","80.014521","-60.940653","4522126666","1500854400","","1500842014000","name","80.014521","-60.996532","sampledevice","3","name"'
values = [convert(value) for value in next(csv.reader(StringIO.StringIO(result)))]

print values

This would then return a list as follows:

['testing', 0.8841, 642000.0, 80.014521, -60.940653, 4522126666L, 1500854400, '', 1500842014000L, 'name', 80.014521, -60.996532, 'sampledevice', 3, 'name']

Python: remove single quotation in a string in a list

This is a simple string replace.

list1[1] = list1[1].replace("'","")

EDIT:
Strings are immutable, so you have to actually do the replace, and reassign. I should add, that by "removing" the single quote, you will not be gaining a space after the comma.

How to remove single quote from a list in python

In your case, the elements are stored as strings in the list res.

You have to convert those elements into numbers.

In this situation python's builtin map(...) function can be used.

Syntax of map:

variable_to_store_new_value = map(type, list_of_elements)

Above code will return a map object. Convert that into a list.

variable = list(map(type, list_of_elements))

Here type can be any valid python data type (str, int, float, etc.) or a function.

Solution to your problem

res = list(map(float, res))

python remove single quotes and spaces from a list

One way to go about this :

result = a[0].replace(' ', '').replace("'", '')[1:].split(',')
print(result)

Output:

['temp1', 'temp12', 'temp3', 'temp4', 'temp5']

How to replace single quotes from a list in python

Your list doesn't contain any strings with single quotes. I think you are confusing the repr() representation of the strings with their values.

When you print a Python standard library container such as a list (or a tuple, set, dictionary, etc.) then the contents of such a container are shown their repr() representation output; this is great when debugging because it makes it clear what type of objects you have. For strings, the representation uses valid Python string literal syntax; you can copy the output and paste it into another Python script or the interactive interpreter and you'll get the exact same value.

For example, s here is a string that contains some text, some quote characters, and a newline character. When I print the string, the newline character causes an extra blank line to be printed, but when I use repr(), you get the string value in Python syntax form, where the single quotes are part of the syntax, not the value. Note that the newline character also is shown with the \n syntax, exactly the same as when I created the s string in the first place:

>>> s = 'They heard him say "Hello world!".\n'
>>> print(s)
They heard him say "Hello world!".

>>> print(repr(s))
'They heard him say "Hello world!".\n'
>>> s
'They heard him say "Hello world!".\n'

And when I echoed the s value at the end, the interactive interpreter also shows me the value using the repr() output.

So in your list, your strings do not have the ' characters as part of the value. They are part of the string syntax. You only need to replace the " characters, they are part of the value, because they are inside the outermost '...' string literal syntax. You could use str.replace('"', '') to remove them:

[value.replace('"', '') for value in my_list]

or, you could use the str.strip() method to only remove quotes that are at the start or end of the value:

[value.strip('"') for value in my_list]

Both work just fine for your sample list:

>>> my_list = ['"3"', '"45"','"12"','"6"']
>>> [value.replace('"', '') for value in my_list]
['3', '45', '12', '6']
>>> [value.strip('"') for value in my_list]
['3', '45', '12', '6']

Again, the ' characters are not part of the value:

>>> first = my_list[0].strip('"')
>>> first # echo, uses repr()
'3'
>>> print(first) # printing, the actual value written out
3
>>> len(first) # there is just a single character in the string
1

However, I have seen that you are reading your data from a tab-separated file that you hand-parse. You can avoid having to deal with the " quotes altogether if you instead used the csv.reader() object, configured to handle tabs as the delimiter. That class automatically will handle quoted columns:

import csv

with open(inputfile, 'r', newline='') as datafile:
reader = csv.reader(datafile, delimiter='\t')
for row in reader:
# row is a list with strings, *but no quotes*
# e.g. ['3', '45', '12', '6']

Demo showing how csv.reader() handles quotes:

>>> import csv
>>> lines = '''\
... "3"\t"45"\t"12"\t"6"
... "42"\t"81"\t"99"\t"11"
... '''.splitlines()
>>> reader = csv.reader(lines, delimiter='\t')
>>> for row in reader:
... print(row)
...
['3', '45', '12', '6']
['42', '81', '99', '11']

How do I strip quotes out of a list of strings?

Simple solution is use the str.replace method twice, to ensure that all types of the quotations are removed.

list1 = ['"22.23.24.25"', "'11.22.33.44'"]

list1 = [x.replace('"', '').replace("'", '') for x in list1]

print(list1)
['22.23.24.25', '11.22.33.44']

remove single quotes in list, split string avoiding the quotes

To get int or float based on what each value looks like, so '1' becomes 1 and "1.2" becomes 1.2, you can use ast.literal_eval to convert the same way Python's literal parser does, so you have an actual list of ints and floats, rather than a list of str (that would include the quotes when echoed):

>>> import ast
>>> [ast.literal_eval(x) for x in l]
[1, 2, 3, 4.5]

Unlike plain eval, this doesn't open security holes since it can't execute arbitrary code.

You could use map for a mild performance boost here (since ast.literal_eval is a built-in implemented in C; normally, map gains little or loses out to list comprehensions), in Py 2, map(ast.literal_eval, l) or in Py3 (where map returns a generator, not a list), list(map(ast.literal_eval, l))

If the goal is purely to display the strings without quotes, you'd just format manually and avoid type conversions entirely:

>>> print('[{}]'.format(', '.join(l)))
[1, 2, 3, 4.5]

Remove single quotes from python list item

Currently all of the values in your list are strings, and you want them to integers, here are the two most straightforward ways to do this:

map(int, your_list)

and

[int(value) for value in your_list]

See the documentation on map() and list comprehensions for more info.

If you want to leave the items in your list as strings but display them without the single quotes, you can use the following:

print('[' + ', '.join(your_list) + ']')


Related Topics



Leave a reply



Submit