How to change part of a variable (string)?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • IanJAl

    How to change part of a variable (string)?

    I have a variable "fileName" = ****.pdb, where the *s are capitalised letters. After a method uses this variable as an argument, I need to change the extension part to .ent without changing the first part. For some reason, none of the str.replace methods seem to work.
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    none of the str.replace methods seem to work.
    Yes they do. Post what you have tried and someone will tell you where you went wrong.

    Comment

    • Glenton
      Recognized Expert Contributor
      • Nov 2008
      • 391

      #3
      If you know it's always that format you can just use:
      Code:
      newstring=fileName[:-3]+"ent"

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Keep in mind strings are immutable. You must reassign the string returned by the replace method to an identifier.
        Code:
        >>> s = "somestring.txt"
        >>> s.replace("txt", "xyz")
        'somestring.xyz'
        >>> s
        'somestring.txt'
        >>> news = s.replace("txt", "xyz")
        >>> news
        'somestring.xyz'

        Comment

        Working...