0

I think that I am getting a key error when accessing a dictionary because some of the keys in the dictionary seem to be strings of strings. Is there a way to strip these to simply be strings?

I was thinking of using a list comprehension but am wondering if there is a better way:

x = ' "string" '
x = [i for i in x if i not in ["'", '"']]
x = ''.join(x)

And now x = 'string'

  • 1
    add sample input and expected output for better clarity – Jay Shankar Gupta Mar 30 '18 at 08:37
  • 2
    Welcome to StackOverflow! Please read the info about [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and [how to give a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). This will make it much easier for others to help you. – Aditi Mar 30 '18 at 08:39
  • 1
    Provide a [mcve]. Odds are you will find the fault yourself while doing that. – Ulrich Eckhardt Mar 30 '18 at 08:39
  • 1
    Possible duplicate of [Remove specific characters from a string in Python](https://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python) – Georgy Mar 30 '18 at 08:53
  • Looks like a x-y problem: you are trying to fix a problem when you should try to avoid it. Where do those ugly `' "string" '` come at first? – Serge Ballesta Mar 30 '18 at 09:12
  • I was given the data in a very ugly format where some of the values had quotation marks around them and some didn't. But yes, this is probably a problem that should never occur. – Karthik Nair Mar 31 '18 at 00:05

3 Answers3

0
x = ' "string" '
x = x.replace('"','\'').replace('\'','\'')
print(x)

Output

'string' 
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27
  • Possibly because it returns strings in the format `"'string'"` I think op just wants the string without any quotes before or after, not sure though. Using replace may also cause problems if the string contains legitimate quotes rather than those at the start and end – Nick is tired Mar 30 '18 at 08:52
0

strip may be useful:

x = x.strip('"\' ')

s.strip([chars]) will remove any of the characters passed to the function from the start and end of the given string and return the result

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
0

You can filter the result :

print("".join(list(filter(lambda _:_.isalpha(),x))))

output:

string

or list comprehension:

print("".join([i for i in x if i.isalpha()]))

output:

string
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88