Select to view content in your preferred language

Remove characters in string using a variable

759
5
Jump to solution
09-16-2022 08:22 AM
jaykapalczynski
Frequent Contributor

I am trying to remove characters from a string but this Numeric value changes.

I'm passing in the string and the number of characters that should remain.

 

Below there are two ways I am trying this both doing the same thing... But the number of characters is hardcoded '75'

How do I replace the '75' with the variable 'characterLength' that is being passed into the def???

 

newmod2 = newmod1[: {characterLength} ]  

 

def fModifyValue(processResults, charlength):
        initialMod = str(processResults)
        characterLength = charlength
        newmod1 = initialMod.replace("u'", "")

        newmod2 = (newmod1[:75] + '..') if len(newmod1) > 75 else newmod1
        #OR 
        newmod2 = newmod1[:75]

        return newmod2

 

0 Kudos
1 Solution

Accepted Solutions
jaykapalczynski
Frequent Contributor

Ok think I got it.... BUT please if there is a better way please let me know.

 

def fModifyValue(processResults, charlength):
        initialMod = str(processResults)
        characterLength = int(charlength)
        newmod1 = initialMod.replace("u'", "").replace('[', '').replace(']', '').replace(r"'", r'')

        newmod2 = newmod1[:characterLength]

        return newmod2

View solution in original post

0 Kudos
5 Replies
jaykapalczynski
Frequent Contributor

Maybe

newmod2 = newmod1[: {} ].format(characterLength)

 

UPDATE:  Nope that does not work

 

0 Kudos
jaykapalczynski
Frequent Contributor

Ok think I got it.... BUT please if there is a better way please let me know.

 

def fModifyValue(processResults, charlength):
        initialMod = str(processResults)
        characterLength = int(charlength)
        newmod1 = initialMod.replace("u'", "").replace('[', '').replace(']', '').replace(r"'", r'')

        newmod2 = newmod1[:characterLength]

        return newmod2
0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Besides the variable length slicing, which you appear to have figured out, what exactly are you trying to do with all of those replace statements?

0 Kudos
jaykapalczynski
Frequent Contributor

The data is coming in from a Word Press RestEP and a bit messy...

0 Kudos
DavidAnderson_1701
Occasional Contributor

Regular expressions are your friend here.  Check out the re module.