How to refactor all occurences of a string into a variable in Python with VSCode

3 weeks ago 25
ARTICLE AD BOX

I don't think VS Code has built-in support for this. I would not recommend this for pretty much anything except string literals, but a simple find-and-replace might honestly be an okay alternative.

Usually, this would be prone to false positives. If you're replacing string literals, however, any false positives would need to be bookended on both sides by quotation marks. I can't think of anything that would cause that except for nested quotes, which are pretty rare.

If you're really worried about false positives, you can always use the advanced find-and-replace menu (the magnifying glass on the left sidebar, or CTRL+SHIFT+H). This will give you a preview of every change before you hit the replace button, which lets you spot those errors beforehand.

Make sure to check for multiple quote styles, of course. Single and double quotes definitely need independent operations (unless you use a regex, which seems overkill). Triple quotes seem unlikely in most cases but might also be worth considering.

There's also a risk of variable name conflicts; if you have a local scope that reuses the global name for the constant, that will need some manual handling. Hopefully, you're choosing a global name that doesn't have that a problem.

Read Entire Article