Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get value of "string"?

Given strings like:

"hello"
'hello'

I want to remove only first and last char if:

  1. They are the same
  2. They are " or '

I.e., given 'hello' I’m expecting hello. Given 'hello" I’m not expecting it to change.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was able to do this by reading first char and last char, validating they are the same + validating they are equal to ' or " and validating it’s not the the same index for char (because I don’t want this: ' to end up as the empty string). With all edge cases checking I ended with 10s of lines.

What’s your approach to solve this?

In simple words, Given a string in Python format I want to return its data and if it’s not valid to keep it as is.

>Solution :

Sounds like a job for regular expressions with groups:

import re
re.sub(r'^([\'"])(.*)(\1)$', r'\2', s)

Which reads as:

  • ^ – match the beginning of the string
  • (['"]) – either single or double quote (group 1)
  • (.*) any (possibly, empty) sequence of characters in between (group 2)
  • (\1) – the same character as in group 1
  • $ – end of the string

If the string matches the pattern above, replace it with the content of the group 2.

For example:

>>> s = re.sub(r'^([\'"])(.*)(\1)$', r'\2', "'hello'")
>>> print(s)
hello

An alternative way could be with ast.literal_eval(), but it won’t handle non-matching quotes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading