简体   繁体   中英

Replacing quotation marks in Python

I have the the following text

text = SCISSOR LIFT 18-19' ELECTRIC 60" LENGTH

I want:

text = SCISSOR LIFT 18-19 FT ELECTRIC 60 INCH LENGTH

I tried text = "SCISSOR LIFT 18-19' ELECTRIC 60" LENGTH" text.replace('"', " ")

But I got

 File "<ipython-input-1-104923c7a47e>", line 1
    text = "SCISSOR LIFT 18-19' ELECTRIC 60" LENGTH"
                                         ^
SyntaxError: invalid syntax

I want to replace the single quotation marks with "FT" and the double quotation marks with inch.

If you want to work with text, you usually read it from file, process it and write to another file (or screen). In this case, there will be no syntax errors related to special characters (like quotes) in the text.

If you want to put your text in the source file itself, as a literal, you have to be careful with special characters. One method to define a string with both single and double quotes is by using triple quotes:

text = '''SCISSOR LIFT 18-19' ELECTRIC 60" LENGTH'''

Here is a python environment session where I checked that it works:

>>> text = '''SCISSOR LIFT 18-19' ELECTRIC 60" LENGTH'''
>>> print(text)
SCISSOR LIFT 18-19' ELECTRIC 60" LENGTH
>>>

If you manage to do this, you are on right track to do your replace-task. Just give correct parameters to your replace function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM