Vorpal Swordsman
Vorpal Swordsman

Reputation: 375

Best way to replace all occurences of a character in a string after the first occurrence

I'm currently doing this:

teststring = "abc-def-ghi-jkl"
pos = teststring.find('-')
newstr = "{}-{}".format(teststring[0:pos], teststring[pos + 1:].replace('-', '_'))

This seems unnecessarily clunky. Is there a more pythonic way to do this?

Upvotes: 2

Views: 77

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114320

You can use str.split:

pre, post = teststring.split('-', 1)
newstr = pre + '-' + post.replace('-', '_')

Like your original solution, this only works if there's at least one - in the string. You can use variable-length argument unpacking to fix this:

*pre, post = 'asdfd--saf'.split('-', 1)
newstr = '-'.join(pre + [post.replace('-', '_')])

Now pre will be either the prefix or an empty list if there are no dashes. post is always the full suffix, with or without dashes.

Upvotes: 4

kaya3
kaya3

Reputation: 51043

Here's a solution using a regex:

>>> import re
>>> re.sub(r'(?<=-)(.*?)-', r'\1_', 'abc-def-ghi-jkl')
'abc-def_ghi_jkl'

It uses a positive lookbehind to match the - character only if another - character appears before it in the string. This is a bit more complicated than the simplest solution using split, but it works correctly even when the input string doesn't contain any - characters.

Upvotes: 1

Related Questions