0

I am trying to pattern match a string, so that if it ends in the characters 'std' I split the last 6 characters and append a different prefix.

I am assuming I can do this with regular expressions and re.split, but I am unsure of the correct notation to append a new prefix and take last 6 chars based on the presence of the last 3 chars.

regex = r"([a-zA-Z])"
if re.search(regex, "std"):
    match = re.search(regex, "std")

#re.sub(r'\Z', '', varname)
1
  • 2
    I think regex is a bit of overkill for this. Try endswith. Commented Jul 10, 2017 at 15:22

2 Answers 2

4

You're confused about how to use regular expressions here. Your code is saying "search the string 'std' for any alphanumeric character".

But there is no need to use regexes here anyway. Just use string slicing, and .endswith:

if my_string.endswith('std'):
    new_string = new_prefix + mystring[-6:]
Sign up to request clarification or add additional context in comments.

Comments

3

No need for a regex. Just use standard string methods:

if s.endswith('std'):
    s = s[:-6] + new_suffix

But if you had to use a regex, you would substitute a regex, you would substitute the new suffix in:

regex = re.compile(".{3}std$")

s = regex.sub(new_suffix, s)

3 Comments

The OP said "new prefix", not "new suffix".
@Błotosmętek He also said "append" instead of "prepend", so I wasn't quite sure.
Sorry for confusion, but yeah it just needs changed to '-6:'

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.