tadm123
tadm123

Reputation: 8787

How to put an argument of a function inside a raw string

I want to create a function that will delete a character in a string of text. I'll pass the string of text and the character as arguments of the function. The function works fine but I don't know how to do this correctly if I want to threat it as a raw string.

For example:

import re

def my_function(text, ch):    
    Regex=re.compile(r'(ch)')   # <-- Wrong, obviously this will just search for the 'ch' characters
    print(Regex.sub('',r'text'))      # <-- Wrong too, same problem as before. 


text= 'Hello there'
ch= 'h'

my_function(text, ch)

Any help would be appreciated.

Upvotes: 0

Views: 230

Answers (2)

Prune
Prune

Reputation: 77837

def my_function(text, ch): 
    text.replace(ch, "")

This will replace all occurrences of ch with an empty string. No need to invoke the overhead of regular expressions in this.

Upvotes: 2

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

How about changing:

Regex=re.compile(r'(ch)')
print(Regex.sub('',r'text'))

to:

Regex=re.compile(r'({})'.format(ch))
print(Regex.sub('',r'{}'.format(text)))

However, simpler way to achieve this is using str.replace() as:

text= 'Hello there'
ch= 'h'
text = text.replace(ch, '')
# value of text: 'Hello tere'

Upvotes: 3

Related Questions