0

I have to replace all of the straight quotation marks (") to curly ones ( or )

I used s.replace to replace all of the straight quotes with curly ones, however, they are all in the same direction. I don't know how to have curly quotes going in one direction when in front of a word, and ones going in the opposite direction at the end.

Ex: '" "o" "i" "' must be converted to '“ “o” “i” ”'

Flimm
  • 136,138
  • 45
  • 251
  • 267
Potion Seller
  • 63
  • 1
  • 8
  • 1
    In theory, you *can't* tell. Is `'""""'` supposed to be `'“”“”'` or `'““””'`? (Open-close-open-close vs open-open-close-close) – chepner Oct 26 '19 at 03:30
  • Does this answer your question? [Ideas for converting straight quotes to curly quotes](https://stackoverflow.com/questions/509685/ideas-for-converting-straight-quotes-to-curly-quotes) – Dave Jarvis Aug 26 '22 at 23:42

3 Answers3

0

You may try this (text is your string):

for i in range(text.count('"')/2+1) :
    text = text.replace( '"', 'open-quote', 1)
    text = text.replace( '"', 'close-quote', 1)

And they all will be replaced.

open-quote and close-quote are used for the easy readability, replace with the actual quote characters you need.

lenik
  • 23,228
  • 4
  • 34
  • 43
0

You can use re and look for pairs of quotes and replace them.

>>> s = "\" \"o\" \"i\" \""
>>> s
'" "o" "i" "'
>>> re.sub(r'(\")(.?)(\")', '“\g<2>”', s)
'“ ”o“ ”i“ ”'
Flimm
  • 136,138
  • 45
  • 251
  • 267
Jab
  • 26,853
  • 21
  • 75
  • 114
0

This seems to work pretty well:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re

def convert_to_curly(string):
    """convert straight quotes to curly ones"""
    string = re.sub(r'\b"',r'”',string)   # closing double on word    
    string = re.sub(r'"\b',r'“',string)   # opening double on word
    string = re.sub(r'\b\'',r'’',string)  # closing single on word
    string = re.sub(r'\'\b',r'‘',string)  # opening single on word

    string = re.sub(r'([^\w\d\s:])"',r'\1”',string)  # closing double on punctuation
    string = re.sub(r'([^\w\d\s:])\'',r'\1’',string) # closing single on punctuation

    string = re.sub(r'\S\'\S',r'’',string)   # apostrophe can be virtually anywhere

    # FIXME: what about single and double quotes not next to word or punctuation? Pairs?

    return(string)