1

I am trying to format a string where the same variable sometimes needs to be appended with new line and tab and other times not.

I don't see any other options but using two different variables, do you think this could be achieved using the same variable?

Example String The actual string is long, and I have may variables which sometimes requires no formatting and sometimes require to appned either new line and tab.

test_str="""
list {values} 
list
    {values} 
"""

for above I want to achieve following output.

list 1,2,3 
list
    1,
    2,
    3 

the current approach, which is not working.

values = ",".join(["1","2","3"])
print test_str.format(values=values)

if I change the values to values1 and values2 then I can apply different formatting.

values1 = ",".join(["1","2","3"])
values2 = ",\n\t".join(["1","2","3"])
print test_str.format(values1=values1, values2=values2)

2 Answers 2

4

This might be what you want.

>>> test_str = '''
... list {}
... list
...     {}
... '''
>>> values
['1', '2', '3']
>>> print(test_str.format(','.join(values), ',\n\t'.join(values)))

list 1,2,3
list
    1,
    2,
    3

Addendum:

Notice that the function creates the string that it returns in the form of a new-fangled f string, thus allowing the possibility of substitution of the values returned by functions or other expressions within it.

>>> def a_string(v1, v2):
...     def f1(val):
...         return '---'+val
...     def f2(val):
...         return '+++'+val
...     return f'''{f1(v1)} is bigger than {f2(v2)}'''
... 
>>> a_string('2', '1')
'---2 is bigger than +++1'
Sign up to request clarification or add additional context in comments.

2 Comments

is there any way I can do with the keyword argument, rather than positional argument. I have to replace lots of parameters not just two in actual string.
I'm not sure that this will meet your purposes. I've added code that uses the f strings that were made available with Python 3.6.
-1

You could use a function to make it possible to use only one set of values as follow

test_str="""
list {values1} 
list
\t{values2} 
"""

def test_format(values):
    values1 = ",".join(values)
    values2 = ",\n\t".join(values)
    return test_str.format(values1=values1, values2=values2)

print test_format(["1", "2", "3"])

1 Comment

question is about using one set of variable. not one set of values. it's hardcoded right now, only coz it's code snippet and not actual code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.