kitchenprinzessin
kitchenprinzessin

Reputation: 1043

Python Regular Expression - Replace String Based Repeated Patterns

I want to transform the string L^2 M T^-1 to L^2.M.T^-1. The dot replaces the space (\s) only if it is between two word characters. For example, if the string is 'lbf / s' no replacement will be applied.

str1= 'L^2 M T^-1'

pattern = re.compile(r'(\w+\s\w+)+')
def pattern_match2(m):
    me = m.group(0).replace(' ', '.')
    return me

pattern.sub(pattern_match2, str1) # this produces L2.MT-1

How can i replace the string with dot (.) by repeated patterns?

Upvotes: 0

Views: 231

Answers (1)

DeepSpace
DeepSpace

Reputation: 81614

You can use re.sub directly instead of finding a match and then using str.replace. Also, I'd use \b instead of \w since \w matches any [a-zA-Z0-9_], while \b encapsulates it in a smarter way (in essence it is equivalent to (^\w|\w$|\W\w|\w\W) )

import re

print(re.sub(r'\b(\s)\b', '.', 'L^2 M T^-1'))
# L^2.M.T^-1

print(re.sub(r'\b(\s)\b', '.', 'lbf / s'))
# lbf / s

Upvotes: 4

Related Questions