• Register
1 vote
41 views

Problem:

I am very noob at programming language so I am doing my pracice on python. I tried to to replace multiple characters in a string in python. So I write this code:

tes_str = "abababababababba"
  
 
print("The main string is : " + str(tes_str)) 
  
 
res = tes_str('a', '%temp%')('b', 'a')('%temp%', 'b') 
  

print("After replacement the string is : " + res) 

But when I run this it shows error:

The main string is : abababababababba
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    res = tes_str('a', '%temp%')('b', 'a')('%temp%', 'b') 
TypeError: 'str' object is not callable

Can anyone help me out?

10 7 2
6,060 points

Please log in or register to answer this question.

2 Answers

1 vote
 
Best answer

Answer:

To replace multiple char in string using python you should use the method

.replace 

you are getting because you did not use this method to replace the char in string . so change your program to:

tes_str = "abababababababba"
  
 
print("The main string is : " + str(tes_str)) 
  
 
res = tes_str.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b') 
  

print("After replacement the string is : " + res) 

And your output will be:

The main string is : abababababababba
After replacement the string is : bababababababaab

Hope this will help you. 

Happy coding.

11 6 4
34,950 points
0 votes

Solution:

Replacing two characters

I attempted all the ways in the present answers along with one extra.

With an input string of abc&def#ghi and replacing & -> \& and # -> \#, the fastest method was to chain together the replacements like this: text.replace('&', '\&').replace('#', '\#').

Timings for every function:

  • a) 1000000 loops, best of 3: 1.47 μs per loop

  • b) 1000000 loops, best of 3: 1.51 μs per loop

  • c) 100000 loops, best of 3: 12.3 μs per loop

  • d) 100000 loops, best of 3: 12 μs per loop

  • e) 100000 loops, best of 3: 3.27 μs per loop

  • f) 1000000 loops, best of 3: 0.817 μs per loop

  • g) 100000 loops, best of 3: 3.64 μs per loop

  • h) 1000000 loops, best of 3: 0.927 μs per loop

  • i) 1000000 loops, best of 3: 0.814 μs per loop

Here are the functions:

def a(text):
    chars = "&#"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['&','#']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('([&#])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('&#')
def e(text):
    esc(text)


def f(text):
    text = text.replace('&', '\&').replace('#', '\#')


def g(text):
    replacements = {"&": "\&", "#": "\#"}
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('&', r'\&')
    text = text.replace('#', r'\#')


def i(text):
    text = text.replace('&', r'\&').replace('#', r'\#')

Timed like this:

python -mtimeit -s"import time_functions" "time_functions.a('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.b('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.c('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.d('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.e('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.f('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.g('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.h('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.i('abc&def#ghi')"

Replacing 17 characters

Here's same code to do the similar however with more characters to escape (\`*_{}>#+-.!$):

def a(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('([\\`*_{}[]()>#+-.!$])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('\\`*_{}[]()>#+-.!$')
def e(text):
    esc(text)


def f(text):
    text = text.replace('\\', '\\\\').replace('`', '\`').replace('*', '\*').replace('_', '\_').replace('{', '\{').replace('}', '\}').replace('[', '\[').replace(']', '\]').replace('(', '\(').replace(')', '\)').replace('>', '\>').replace('#', '\#').replace('+', '\+').replace('-', '\-').replace('.', '\.').replace('!', '\!').replace('$', '\$')


def g(text):
    replacements = {
        "\\": "\\\\",
        "`": "\`",
        "*": "\*",
        "_": "\_",
        "{": "\{",
        "}": "\}",
        "[": "\[",
        "]": "\]",
        "(": "\(",
        ")": "\)",
        ">": "\>",
        "#": "\#",
        "+": "\+",
        "-": "\-",
        ".": "\.",
        "!": "\!",
        "$": "\$",
    }
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('\\', r'\\')
    text = text.replace('`', r'\`')
    text = text.replace('*', r'\*')
    text = text.replace('_', r'\_')
    text = text.replace('{', r'\{')
    text = text.replace('}', r'\}')
    text = text.replace('[', r'\[')
    text = text.replace(']', r'\]')
    text = text.replace('(', r'\(')
    text = text.replace(')', r'\)')
    text = text.replace('>', r'\>')
    text = text.replace('#', r'\#')
    text = text.replace('+', r'\+')
    text = text.replace('-', r'\-')
    text = text.replace('.', r'\.')
    text = text.replace('!', r'\!')
    text = text.replace('$', r'\$')


def i(text):
    text = text.replace('\\', r'\\').replace('`', r'\`').replace('*', r'\*').replace('_', r'\_').replace('{', r'\{').replace('}', r'\}').replace('[', r'\[').replace(']', r'\]').replace('(', r'\(').replace(')', r'\)').replace('>', r'\>').replace('#', r'\#').replace('+', r'\+').replace('-', r'\-').replace('.', r'\.').replace('!', r'\!').replace('$', r'\$')

Here's the results for the similar input string abc&def#ghi:

  • a) 100000 loops, best of 3: 6.72 μs per loop

  • b) 100000 loops, best of 3: 2.64 μs per loop

  • c) 100000 loops, best of 3: 11.9 μs per loop

  • d) 100000 loops, best of 3: 4.92 μs per loop

  • e) 100000 loops, best of 3: 2.96 μs per loop

  • f) 100000 loops, best of 3: 4.29 μs per loop

  • g) 100000 loops, best of 3: 4.68 μs per loop

  • h) 100000 loops, best of 3: 4.73 μs per loop

  • i) 100000 loops, best of 3: 4.24 μs per loop

And with a longer input string (## *Something* and thing in a longer sentence with {more} things to replace$):

  • a) 100000 loops, best of 3: 7.59 μs per loop

  • b) 100000 loops, best of 3: 6.54 μs per loop

  • c) 100000 loops, best of 3: 16.9 μs per loop

  • d) 100000 loops, best of 3: 7.29 μs per loop

  • e) 100000 loops, best of 3: 12.2 μs per loop

  • f) 100000 loops, best of 3: 5.38 μs per loop

  • g) 10000 loops, best of 3: 21.7 μs per loop

  • h) 100000 loops, best of 3: 5.7 μs per loop

  • i) 100000 loops, best of 3: 5.13 μs per loop

Including a couple of variants:

def ab(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        text = text.replace(ch,"\\"+ch)


def ba(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        if c in text:
            text = text.replace(c, "\\" + c)

With the shorter input:

  • ab) 100000 loops, best of 3: 7.05 μs per loop

  • ba) 100000 loops, best of 3: 2.4 μs per loop

With the longer input:

  • ab) 100000 loops, best of 3: 7.71 μs per loop

  • ba) 100000 loops, best of 3: 6.08 μs per loop

hence I'm going to employ ba for readability and speed.

Addendum

Ensouled by haccks in the comments, one distinction between ab and ba is the if c in text: check. Let's test them against two more variants:

def ab_with_check(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)

def ba_without_check(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)

Times in μs per loop on Python 2.7.14 and 3.6.3, and on a diverse machine from the earlier fixed, hence cannot be compared directly.

Py, input  ║  ab  │ ab_with_check │  ba  │ ba_without_check │
╞════════════╬══════╪═══════════════╪══════╪══════════════════╡
│ Py2, short ║ 8.81 │    4.22       │ 3.45 │    8.01          │
│ Py3, short ║ 5.54 │    1.34       │ 1.46 │    5.34          │
├────────────╫──────┼───────────────┼──────┼──────────────────┤
│ Py2, long  ║ 9.3  │    7.15       │ 6.85 │    8.55          │
│ Py3, long  ║ 7.43 │    4.38       │ 4.41 │    7.02          │

We can finish that:

  • Those with the inspection are up to 4x faster than those without the inspection

  • ab_with_check is slightly in the lead on Python 3, however ba (with check) has a greater lead on Python 2

  • But, the biggest lesson here is Python 3 is up to 3x faster than Python 2! There's not a huge distinction between the slowest on Python 3 and fastest on Python 2!

 

10 6 4
31,120 points

Related questions

1 vote
1 answer 28 views
28 views
Problem: I have a simple and basic level question to you guy. How can I replace an element in a list python? Yeah, it might be a silly question but need to be answered badly. I am struggling with this problem for the last thirty minutes almost. But I am unable to sort out this thing. Your kind help is much needed. Thanks
asked Apr 4, 2020 Gavin 15.3k points
0 votes
1 answer 70 views
0 votes
1 answer 18 views
18 views
I require to remove all the special characters, puntuation and and speces from a string?
asked Sep 14, 2020 Daniel Anderson 4k points
2 votes
1 answer 46 views
46 views
Problem: Well, let&rsquo;s assume I have a string in python and I am willing to remove all the duplicates characters from my string. Suppose my string is &ldquo;Australia&rdquo; the program should return &ldquo;Austrli&rdquo; So, my question is simple. How can I remove duplicate characters in a string python?
asked Apr 5, 2020 Gavin 15.3k points
0 votes
1 answer 8 views
8 views
Problem: Hi my friends i am begginer and i want to know how i do that please explain to me with example if you dont explain with example no explain please thank you
asked Feb 9 ahmedadel9090 3.1k points
0 votes
1 answer 3 views
3 views
Problem: Please help me with my homework query. I am stuck. How to remove characters from a string python?
asked Apr 2 Sana8989 8.9k points
1 vote
1 answer 40 views
40 views
Problem: Hi all, I am a novice in python programming. I got a problem in the textbook exercise I was learning from. It says to remove all special characters from string python. I&rsquo;ve tried several ways that didn&rsquo;t work for me. Unfortunately, I removed all the char from my string. So, what is the best practice to do it if it is doable? Thanks for your valuable time. Best regards.
asked Apr 5, 2020 Gavin 15.3k points
0 votes
1 answer 29 views
29 views
Problem: I am trying to count the occurrences of each letter of a word word = input("Enter a word") Alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w',' ... ): print(word.count(Alphabet[i])) This currently outputs the number of times each letter occurs including the ones that don't. How do I list the letters vertically with the frequency alongside
asked Jan 22 Mashhoodch 13k points
0 votes
1 answer 2 views
2 views
Problem: how to I Solve this: convert list of characters to string python HELP! I need help understanding this: convert list of characters to string python Can someone please help solve this, I am new in python(). Someone have idea to solve this thanks!
asked Mar 10 Mashhoodch 13k points
0 votes
1 answer 7 views
7 views
Problem: how to I Solve this: convert string to list of characters python HELP! I need help understanding this: convert string to list of characters python Can someone please help solve this, I am new in python(). Someone have idea to solve this thanks!
asked Mar 8 Mashhoodch 13k points