Udit Dey
Udit Dey

Reputation: 183

Converting strings

I don't think many people would have a question like this, but still.

So, I have a python program which reads a file, and the file has some commands for the program to do (my own syntax).
The program reads the file line by line to a string.
What if the command it reads from the file is:

'"Hello" + "World" + "!!!"'

I want to convert this to:

"Hello" + "World" + "!!!"

So that python can read it as:

'HelloWorld!!!'

Despite many attempts, I have been unable to do so.
Help would be loved.

One thing I've tried is executing the code with the compile function:

obj = compile('a = '"Hello" + "World" + "!!!"'', '<string>', 'exec')
exec(obj)
print a

But instead of 'HelloWorld!!!' it prints "Hello" + "World" + "!!!", and by putting it in a string it goes back to '"Hello" + "World" + "!!!"'.


NOTE: The program might even come across variables. For example:

a = 42
'"The number" + "is" + a'

Expected output:

The number is 42

What can be done in this case?

Upvotes: 1

Views: 54

Answers (3)

Peter Westlake
Peter Westlake

Reputation: 5036

Your mistake is putting it back into a string. Compiling and evaluating has taken off one level of quoting, so now you need to repeat the process. You can use the "eval" function instead of compiling an assigment, like this:

for line in open(your file....):
    print eval(eval(line))

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107347

You can use shlex module in order to split the string using shell-like syntax then use a list comprehension within str.join() method to concatenate the words:

>>> import shlex
>>> 
>>> ''.join([i for i in shlex.split(s) if i != '+'])
'HelloWorld!!!'

Note that you can simply use eval() function on the string, but it's not a safe approach at all. Unless you are sure that the string is not contain the dangerous commands.

Upvotes: 0

Avi&#243;n
Avi&#243;n

Reputation: 8396

You can use the following trick:

m = '"Hello" + "World" + "!!!"'
print ''.join(m.replace('"', "").split(" + "))

Outputs:

HelloWorld!!!

First you replace the ", then make a list with only the words with .split and then generate a string from the list with ''.join()

Upvotes: 1

Related Questions