Reputation: 31
how can i replace the double quotation marks with the stylistically correct quotation marks („ U+201e or “ U+201c ) according to German spelling.
example:
zitat = 'Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"'
I've tried the code
import re
zitatnew = re.sub(r'"', r'[u+201e]', zitat)
print(zitatnew)
Laut Durkheim ist ein [u+201e]soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt[u+201e]
How can i replace the double quotations marks with the correct one using unicode?
Maybe one of you can help me. P.S. I'm sorry for my bad english!
Upvotes: 1
Views: 624
Reputation: 177600
re.sub
is more efficient than replacing over and over, and with a replacement function it can be done in one pass:
import re
s = '"this" "is" "a" "test" "string"'
s = re.sub(r'(\b")|("\b)',lambda m: '\u201c' if m.group(1) else '\u201e',s)
print(s)
„this“ „is“ „a“ „test“ „string“
Upvotes: 0
Reputation: 8564
I guess you are looking for this
re.sub(r'"', u"\u201E", zitat)
or the more appropriate
s = 'Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"'
# substitute the opening quote
output = re.sub('\B"', u"\u201C", s)
# substitute the closing quote as well
output = re.sub('"\B', u"\u201D", output)
>>> output
'Laut Durkheim ist ein “soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt”'
which gives
'Laut Durkheim ist ein “soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt”'
Upvotes: 1
Reputation: 4099
You can iterate while there are "
in the string and in every iteration replace one pair of quotes:
zitat = 'Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"'
print(f"Before replace: {zitat}")
while "\"" in zitat:
zitat = zitat.replace("\"", "\u201e", 1)
zitat = zitat.replace("\"", "\u201c", 1)
print(f"After replace: {zitat}")
The 1
as third argument in replace()
is important to replace only the first ocurrence of the "
. This should give a correct output for any string with an even number of "
.
Output:
Before replace: Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"
After replace: Laut Durkheim ist ein „soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt“
Upvotes: 1