Aanhalingstekens
Strings kunnen worden ingesloten in zowel enkele aanhalingstekens ('...')
als dubbele aanhalingstekens ("...")
. Als je echter aanhalingstekens binnen je string moet gebruiken, moet je voorzichtig zijn om syntaxfouten te vermijden.
# This will raise a syntax error due to the apostrophe inside single quotes transaction_note = 'Today's payment was delayed' print(transaction_note)
Python interpreteert de apostrof '
in "Today's"
als het einde van de string, wat verwarring veroorzaakt in de rest van de regel.
Juiste manieren om aanhalingstekens binnen strings te gebruiken
Gebruik dubbele aanhalingstekens buiten als de string een apostrof bevat:
# Using double quotes allows us to include an apostrophe safely transaction_note = "Today's payment was delayed" print(transaction_note)
Gebruik enkele aanhalingstekens buiten als de string dubbele aanhalingstekens bevat:
# Using single quotes to include a quote in the text audit_remark = 'The client said: "We will send the invoice tomorrow."' print(audit_remark)
Gebruik driedubbele aanhalingstekens om beide soorten aanhalingstekens op te nemen
Driedubbele aanhalingstekens ('''...'''
of """..."""
) worden vaak gebruikt voor tekst over meerdere regels, maar ze zijn ook handig wanneer een string zowel enkele als dubbele aanhalingstekens bevat:
# Triple quotes allow both single and double quotation marks financial_summary = """Today's report includes the note: "Check the 'Q1' revenue drop." """ print(financial_summary)
Praktisch Boekhoudkundig Voorbeeld
# Correct use of quotes to log an accountant's comment comment = "The accountant's note: 'Double-check the tax deduction before approval.'" print(comment) # Using triple quotes to format a longer, multi-line report comment report_comment = """ Manager's instructions: - Review the 'Accounts Receivable' section. - Confirm with the accountant: "Is the write-off policy still valid?" """ print(report_comment)
Deze aanpak zorgt ervoor dat je strings syntactisch correct zijn en verbetert de leesbaarheid van de code, vooral wanneer je werkt met financiële gegevens uit de praktijk die aanhalingen in documentatie of opmerkingen kunnen bevatten.
Swipe to start coding
De zin hieronder bevat zowel enkele aanhalingstekens als gewone tekst. Om het een geldige string in Python te maken, voeg de juiste aanhalingstekens rond de zin toe. Je kunt een van de eerder beschreven methoden gebruiken (dubbele aanhalingstekens buiten, of drievoudige aanhalingstekens).
Oplossing
Bedankt voor je feedback!