I noticed that my code has many statements like this:
var = "some_string"
var = some_func(var)
var = another_func(var)
print(var) # outputs "modified_string"
It's really annoying me, it just looks awful (in the opposite of whole Python). How to avoid using that and start using it in a way like this:
var = "some_string"
modify(var, some_func)
modify(var, another_func)
print(var) # outputs "modified_string"
The C library function to copy a string is strcpy(), which (I'm guessing) stands for string copy.
When it is required to replicate the duplicate occurrence in a string, the keys, the 'index' method and list comprehension can be used. The list comprehension is a shorthand to iterate through the list and perform operations on it.
There are two ways for changing any data type into a String in Python : Using the str() function. Using the __str__() function.
That might not be the most "pythonic" thing to do, but you could "wrap" your string in a list, since lists are mutable in Python. For example:
var = "string"
var_wrapper = [var]
Now you can pass that list to functions and access its only element. When changed, it will be visible outside of the function:
def change_str(lst):
lst[0] = lst[0] + " changed!"
and you'll get:
>>> change_str(var_wrapper)
>>> var_wrapper[0]
"string changed!"
To make things a bit more readable, you could take it one step further and create a "wrapper" class:
class my_str:
def __init__(self, my_string):
self._str = my_string
def change_str(self, new_str):
self._str = new_str
def __repr__(self):
return self._str
Now let's run the same example:
>>> var = my_str("string")
>>> var
string
>>> var.change_str("new string!")
>>> var
new string!
* Thanks for @Error-SyntacticalRemorse for the remark of making a class.
The problem is that str
, int
and float
(long
too, if you're in Py 2.x (True and False are really int
s, so them too)) are what you call 'immutable types' in Python. That means that you can't modify their internal states: all manipulations of an str
(or int
or float
) will result in a "new" instance of the str
(or whatever) while the old value will remain in Python's cache until the next garbage collection cycle.
Basically, there's nothing you can do. Sorry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With