Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert, or unformat, a string to variables (like format(), but in reverse) in Python

I have strings of the form Version 1.4.0\n and Version 1.15.6\n, and I'd like a simple way of extracting the three numbers from them. I know I can put variables into a string with the format method; I basically want to do that backwards, like this:

# So I know I can do this: x, y, z = 1, 4, 0 print 'Version {0}.{1}.{2}\n'.format(x,y,z) # Output is 'Version 1.4.0\n'  # But I'd like to be able to reverse it:  mystr='Version 1.15.6\n' a, b, c = mystr.unformat('Version {0}.{1}.{2}\n')  # And have the result that a, b, c = 1, 15, 6 

Someone else I found asked the same question, but the reply was specific to their particular case: Use Python format string in reverse for parsing

A general answer (how to do format() in reverse) would be great! An answer for my specific case would be very helpful too though.

like image 863
evsmith Avatar asked Aug 07 '12 11:08

evsmith


People also ask

What is format () in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

How do you escape a format in Python?

You can use the backslash (\) escape character to add single or double quotation marks in the python string format. The \n escape sequence is used to insert a new line without hitting the enter or return key.

What is the alternative of format in Python?

. format() is OK, even with one variable. In python 3.6 you can also use: print(f"I am at {location} right now.")

What does format return in Python?

The format() function returns a formatted representation of a given value specified by the format specifier.


2 Answers

Just to build on Uche's answer, I was looking for a way to reverse a string via a pattern with kwargs. So I put together the following function:

def string_to_dict(string, pattern):     regex = re.sub(r'{(.+?)}', r'(?P<_\1>.+)', pattern)     values = list(re.search(regex, string).groups())     keys = re.findall(r'{(.+?)}', pattern)     _dict = dict(zip(keys, values))     return _dict 

Which works as per:

>>> p = 'hello, my name is {name} and I am a {age} year old {what}'  >>> s = p.format(name='dan', age=33, what='developer') >>> s 'hello, my name is dan and I am a 33 year old developer' >>> string_to_dict(s, p) {'age': '33', 'name': 'dan', 'what': 'developer'}  >>> s = p.format(name='cody', age=18, what='quarterback') >>> s 'hello, my name is cody and I am a 18 year old quarterback' >>> string_to_dict(s, p) {'age': '18', 'name': 'cody', 'what': 'quarterback'} 
like image 170
DanH Avatar answered Oct 04 '22 10:10

DanH


>>> import re >>> re.findall('(\d+)\.(\d+)\.(\d+)', 'Version 1.15.6\n') [('1', '15', '6')] 
like image 36
Willian Avatar answered Oct 04 '22 11:10

Willian