0

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 a dot (.) by repeated patterns?

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.