Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3677360
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T03:12:44+00:00 2026-05-19T03:12:44+00:00

I use Python 2.6 and I want to replace each instance of certain leading

  • 0

I use Python 2.6 and I want to replace each instance of certain leading characters (., _ and $ in my case) in a string with another character or string. Since in my case the replacement string is the same, I came up with this:

def replaceLeadingCharacters(string, old, new = ''):
    t = string.lstrip(old)

    return new * (len(string) - len(t)) + t

which seems to work fine:

>>> replaceLeadingCharacters('._.!$XXX$._', '._$', 'Y')
'YYY!$XXX$._'
  • Is there a better (simpler or more efficient) way to achieve the same effect in Python ?

  • Is there a way to achieve this effect with a string instead of characters? Something like str.replace() that stops once something different than the string-to-be-replaced comes up in the input string? Right now I’ve come up with this:

    def replaceLeadingString(string, old, new = ''):
        n = 0
        o = 0
        s = len(old)
    
        while string.startswith(old, o):
            n += 1
            o += s
    
        return new * n + string[o:]
    

    I am hoping that there is a way to do this without an explicit loop

EDIT:

There are quite a few answers using the re module. I have a couple of questions/issues with it:

  • Isn’t it significantly slower than the str methods when used as a replacement for them?

  • Is there an easy way to properly quote/escape strings that will be used in a regular expression? For example if I wanted to use re for replaceLeadingCharacters, how would I ensure that the contents of the old variable will not mess things up in ^[old]+ ? I’d rather have a “black-box” function that does not require its users to pay attention to the list of characters that they provide.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T03:12:44+00:00Added an answer on May 19, 2026 at 3:12 am

    Your replaceLeadingCharacters() seems fine as is.

    Here’s replaceLeadingString() implementation that uses re module (without the while loop):

    #!/usr/bin/env python
    import re
    
    def lreplace(s, old, new):
        """Return a copy of string `s` with leading occurrences of
        substring `old` replaced by `new`.
    
        >>> lreplace('abcabcdefabc', 'abc', 'X')
        'XXdefabc'
        >>> lreplace('_abc', 'abc', 'X')
        '_abc'
        """
        return re.sub(r'^(?:%s)+' % re.escape(old),
                      lambda m: new * (m.end() / len(old)),
                      s)
    

    Isn’t it significantly slower than the str methods when used as a replacement for them?

    Don’t guess. Measure it for expected input.

    Is there an easy way to properly quote/escape strings that will be used in a regular expression?

    re.escape()

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to use some Python libraries to replace MATLAB. How could I import
I'm writing a custom dice rolling parser (snicker if you must) in python. Basically,
I want to load a CSV file that looks like this: Acct. No.,1-15 Days,16-30
I'm building a set of SVG files that include an unfortunate number of hardcoded
I'm trying to extract text from arbitrary html pages. Some of the pages (which
Basically, I do lots of one-off code generation, large-scale refactorings, etc. etc. in Java.
In one of my current side projects, I am scanning through some text looking
I was recently thinking how I'm not always using the beautiful concepts of OO
Table structure - Data present for 5 min. slots - data_point | point_date 12
I currently have a client website on the Grid server on MediaTemple that will

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.