single-quoted string conversion to triple-quoted string

Bengt Richter bokr at oz.net
Sat Apr 6 23:58:38 EST 2002


On 7 Apr 2002 03:18:58 GMT, bokr at oz.net (Bengt Richter) wrote:

>On Sat, 06 Apr 2002 01:45:32 GMT, "Emile van Sebille" <emile at fenx.com> wrote:
>
>>"robin and jim" <robinjim at earthlink.net>
>>> Is there a way to convert a single quoted string to a triple quoted
>>string?
>>>
>>> For example, given:
>>>
>>> ''' abc %d xyz '''
>>>
>>> the result of ''' abc %d xyz''' % 10 is:
>>>
>>> ' abc 10 xyz '
>>>
>>> which is a single quoted string.
>>>
>>> I would like to convert the result to a triple-quoted string.
>>>
>>>
>>
>>What do you want to do with it?  Once a string is created, it doesn't
>>matter which style quoting was used -- it's simply a string.
>>
>True, but notice:
>
> >>> """ ' """
> " ' "
> >>> """ " """
> ' " '
> >>> """ ' " """
> ' \' " '
> >>>
>
>perhaps he would have liked """ ' " """ back instead of ' \' " '
>Seems like just as valid as switching the other quotes, e.g., a quick hack
>to simulate extending the quote-choosing of repr:
>
> >>> def repr3(x):
> ...     rep = repr(x)
> ...     if rep.find('\\n')<0 and rep[1:-1].find("\\'")<0: return rep
> ...     rep=rep[1:-1].replace('\\n','\n')
> ...     rep=rep.replace("\\'","'")
> ...     return '"""' + rep + '"""'
> ...
> >>> tests = [""" ' """, """ " """, """ ' " """, """Line 1
> ... Line 2"""]
> >>> for t in tests: print 'plain: %s\n repr: %s\nrepr3: %s\n'% (t, repr(t), repr3(t))
> ...
> plain:  '
>  repr: " ' "
> repr3: " ' "
>
> plain:  "
>  repr: ' " '
> repr3: ' " '
>
> plain:  ' "
>  repr: ' \' " '
> repr3: """ ' " """
>
> plain: Line 1
> Line 2
>  repr: 'Line 1\nLine 2'
> repr3: """Line 1
> Line 2"""
>
Well, it needs some logic for handling embedded triple quotes, and preventing
unescaping from creating unintended triples quotes in the representation, but
I don't have time right now ... it was a "quick hack" ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list