Python Forum
why does str need a .replace() method?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why does str need a .replace() method?
#1
why does str need a .replace() method? is code any longer if, instead, there is a builtin function replace() that takes 3 arguments?

of course, it's too late to change it, now.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
hmm
>>> replace
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'replace' is not defined
this is Python 3.10.6
Reply
#3
well, yeah, it's not in Python. i'm just saying it could have been that way, instead of being a str method. it would just change the syntax, making it no longer. then it could be used on other sequence types, as well, without having to add a method to list and tuple.

or maybe 1.37% fewer programmers could grasp understanding it if it were not a method.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
(Oct-24-2022, 10:49 PM)Skaperen Wrote: it could be used on other sequence types
How would you define replace() for lists? Would it replace a sublist by another sublist?
Reply
#5
(Oct-25-2022, 07:58 AM)Gribouillis Wrote: How would you define replace() for lists? Would it replace a sublist by another sublist?

it would create a new list or tuple with every item that matches the 2nd to last argument substituted with (maybe a copy or deep copy of) the last argument. match might be "==" or "is" (whatever "in" does). it would then return the substituted sequence. if bytearray gets modified in place then the reason for that might also apply to list (but, obviously, not to tuple).

if a list is given as the 2nd to last argument in that replace call, any matching list would get substituted. is that what you mean by sublist? this substitution probably should be by reference.

i would not mind to add a couple more optional arguments to specify the extent to make substitutions (outside that range is copied unreplaced).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020