Removing single quotes from beginning and end of output

Question:

Is there any way of removing single quotes from the beginning and the end of the output string or list? I tried replace("'",""), but that does not seem to work for certain reason.

The replace function worked while processing the input but I am puzzled why it does not work for the output.

For example, the code block below:

    really_final_output = str(final_output).replace("'","")
    return really_final_output

should generate something along the lines of:

1, 2, 3, 4, 5, 6, 7, 8, 9

instead of:

'1, 2, 3, 4, 5, 6, 7, 8, 9'
Asked By: simguy

||

Answers:

You simply can’t remove it because if you remove it from a string it won’t be a string anymore.

To get only the values you must string.split(‘,’) and you will get a list of all elements which can then be converted to integers or floats.

string = '1, 2, 3'
numbers = list(map(int, string.split(',')))

The argument passed to split() is the character on which you want to split.

Now, if you are trying to get say all numbers from keyboard input you can do something like this:

numbers = list(map(int, input("Input message: ").split()))

Here a good reference to practice and learn more about the string split method: https://www.w3schools.com/python/ref_string_split.asp

Answered By: Arthur Querido

Is there any way of removing single quotes … ?

Yes.

In interactive use, the REPL will quote certain displayed results
as an aid to copy-n-pasting them back into new expressions.
Invoke print( ... ) in the REPL so you won’t see those surrounding quotes.

>>> [7, 8, 9]
[7, 8, 9]
>>>
>>> str([7, 8, 9])
'[7, 8, 9]'
>>>
>>> print(str([7, 8, 9]))
[7, 8, 9]
>>>
>>> s = """a'b"c"""
>>> s
'a'b"c'
>>>
>>> print(s)
a'b"c

If you have some expression s and you don’t want to see
quotes around it, then avoid typing >>> s RETURN at the
REPL prompt. Instead, use >>> print(s).


OTOH to remove quotes that are within a string expression you’d want
.strip().

def remove_quotes(s: str):
    return s.strip("'")

Usage:

print(remove_quotes("'What a curious feeling!' said Alice; 'I must be shutting up like a telescope.'"))

output:

What a curious feeling!' said Alice; 'I must be shutting up like a telescope.

Notice that .strip accepts character sets,
so we might usefully discard punctuation with .strip(";,.").
If you want to remove a word, prefer the
.remove{prefix,suffix}
methods.

Answered By: J_H
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.