0

I want to add '-' after every char in string except at start and end.

Example- Input - 'abcd' Expected Output - 'a-b-c-d' I tried -

Str1 = re.sub(r'([a-z])([a-z])',r'\1-\2',Str1)

What am I doing wrong?

0

2 Answers 2

2

Use str.join

Ex:

s = 'abcd'
print("-".join(s))
# --> a-b-c-d
Sign up to request clarification or add additional context in comments.

Comments

0

Using string join is probably the best option here, but if you wanted to stick with your regex approach, here is one way to do it:

inp = "abcd"
output = re.sub(r'([a-z])(?!$)', '\\1-', inp)
print(output)

This prints:

a-b-c-d

The idea here is to capture each letter and replace with that letter, followed by a dash, if the letter be not the final letter in the string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.