Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change string value by function [duplicate]

Tags:

python

string

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"
like image 865
impress_meh Avatar asked Jun 17 '11 23:06

impress_meh


People also ask

Which function duplicates a string?

The C library function to copy a string is strcpy(), which (I'm guessing) stands for string copy.

How do you replace duplicates in a string in python?

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.

How do you change a function to a string in Python?

There are two ways for changing any data type into a String in Python : Using the str() function. Using the __str__() function.


2 Answers

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.

like image 116
Tomerikoo Avatar answered Sep 19 '22 03:09

Tomerikoo


The problem is that str, int and float (long too, if you're in Py 2.x (True and False are really ints, 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.

like image 26
cwallenpoole Avatar answered Sep 20 '22 03:09

cwallenpoole