Python Forum

Full Version: Change values in string multiline
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
my question is the following.

can we change the value of some information in a multiline string?

I tested the format but it does not work.

self._values = """
          {
            "email": "{VALUE CHANGE}",
            "password": "{Value Change}"
          }
        """
Thank you
Hello,
strings in Python aren't really meant to be used that way, there are better options.
Formatting surely is one of them. For example, you can make a function that converts/formats data from a dictionary to a string like you have. Or use JSON etc...
But for your case I think string's replace method would be best suitable.
(website with example)
You may want to throw in some substring search + offsetting and slicing to get your result. But again, it is really cumbersome.
Could you show what your string looks like and what you want to replace. It's not very clear what you want to achieve.
Your example looks like json string or some kind of unsuccessful attempt at using string formatting
self._values = """
          {
            "email": "[email protected]",
            "password": "12345"
          }
        """
I would like to change [email protected] by a string contained in a variable

the same for the password
OK, this is json string

import json
values = """
          {
            "email": "[email protected]",
            "password": "12345"
          }
        """

my_values = json.loads(values)
my_values['email'] = '[email protected]'
my_values['password'] = '54321'

# print it as json
print(my_values)

#dump back as string
values = json.dumps(my_values, indent=2, sort_keys=True)
# print string values
print(values)
print(type(values))
Output:
{'email': '[email protected]', 'password': '54321'} { "email": "[email protected]", "password": "54321" } <class 'str'>

by the way, where the original string comes from? maybe you don't process it 'correctly' in the first place to end up with string.