josephsmendoza
josephsmendoza

Reputation: 17

Python Find all letter chars in string and surround with text

So lets say I have a string that says "m * x + b", I want to find any letter chars, other than x, and surround them with text.

In this example, output should be "var['m'] * x + var['b']"

Upvotes: 0

Views: 258

Answers (1)

Falko
Falko

Reputation: 17917

A tiny regular expression solves your problem:

import re

s = "m * x + b"
print re.sub("([a-wyzA-Z])", r"var['\1']", s)

Output:

var['m'] * x + var['b']

Explanation:

  • [a-wyzA-Z] matches all characters within the brackets: a-w, y, z and A-Z (so basically every letter but x)
  • (...) makes the found match accessible later via \1
  • r"var['\1']" is the replacement referring to the match\1`

Upvotes: 1

Related Questions