Reputation: 85
First of all, I apologize for my vague question framing, I just couldn't figure out what to call this question. I have also searched google a lot trying to find the solution but I came to no conclusion.
I currently have a whole string with numbers like these 15-5.{123434}.15-18.
. I want to iterate over the string, and as soon as I encounter an opening curly brace I want to take all of numbers after that before encountering a closing brace and put them in a variable. I have thought of a way of doing this, like this:
string = '15-5.{123434}.15-18.'
result = ""
for index, letter in enumerate(string): # For every letter with it's index,
if letter == '{': # If letter is '{',
for number in string[index:]: # Start a loop from that index,
if number =='}': # If number becomes '}',
break
result += number #Else append the number in the result string.
However, I was wondering if there was a better way of doing this. I appreciate all of the answers. Thank you!
System: Windows 10, 32bit Python version: 3.6.0
Upvotes: 0
Views: 253
Reputation: 3741
not knocking a regex but I think I found another one-liner with .split()
[e.split('}')[0] for e in s.split('{') if '}' in e]
testing:
ss = ['','{}','{0}','1','{0}1','1{0}','{0}{2}','{0}1{2}','{0}1{2}3']
for s in ss:
print(s,[e.split('}')[0] for e in s.split('{') if '}' in e])
[]
{} ['']
{0} ['0']
1 []
{0}1 ['0']
1{0} ['0']
{0}{2} ['0', '2']
{0}1{2} ['0', '2']
{0}1{2}3 ['0', '2']
edited to expand on list comprehensions
plenty of info available on list comprehensions, http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ is very basic, enough to understand my answer's list comprehension
we can rewrite the comprehension with line breaks between its parts which may help reading it:
c = [e.split('}')[0]
for e in s.split('{')
if '}' in e]
and we can do the whole thing in the equivalent for loop:
def in_curly(s):
new_list = []
for e in s.split('{'):
if '}' in e:
new_list.append(e.split('}')[0])
return new_list
c = in_curly(s)
with say:
s ='35{0}17{2}3'
either or both of the above can be stepped through in http://pythontutor.com live execution visualization mode
Upvotes: 1
Reputation: 114035
This is one of the few times I'll recommend a regex:
In [27]: for i in re.findall("\{\d+\}", '15-5.{123434}.15-18.'): print(i[1:-1])
123434
Of course, you could write a function to parse it yourself:
def getNums(s):
answer = []
curr = []
acc = False
for char in s:
if char == "{":
acc = True
continue
if char == "}":
acc = False
answer.append(''.join(curr))
acc = False
continue
if acc:
curr.append(char)
Upvotes: 4