Skip to content Skip to sidebar Skip to footer

How Do I Get Python To Detect A Right Brace, And Put A Space After That?

beginner python programmer here. For my homework, I need the computer to identify the right brace '}' in this one conjoined string and seperate all of them into individual componen

Solution 1:

Another possible way is using a regex finder in your string.

import re
your_string = '(->{200}, o^{90}, ->{200}, o^{90}, ->{200}, o^{90}, ->{200}, o^{90})'# List of characters inside brackets

result_list = re.findall(r'{[0-9]+}', your_string)
print(result_list)
# result_list will look something like this based on your example
['{200}', '{90}', '{200}', '{90}', '{200}', '{90}', '{200}', '{90}']

You can change the part inside the single quotes {[0-9]+} depending on the kind of values you expect inside the brackets. For example "(->{[0-9]+}|o\^{[0-9]+})" will return a list of both ->{XXX} and o^{YYY}

['->{200}', 'o^{90}', '->{200}', 'o^{90}', '->{200}', 'o^{90}', '->{200}', 'o^{90}']

Keep in mind that findall function returns a list so you can work on each individual match however you like.

Solution 2:

Try this:

>>> s = '->{200}o^{90}->{200}o^{90}->{200}o^{90}!0->{200}o^{90}'
>>> v = [i+'}'foriin s.split('}')]
>>> v
['->{200}', 'o^{90}', '->{200}', 'o^{90}', '->{200}', 'o^{90}', '!0->{200}', 'o^{90}', '}']

Note that this adds an extra brace at end of array. Just remove that with

>>>v = v[0:-1]

Edit: Or make it even better with @MrFuppes suggestion to avoid post-formatting:

>>>v = [i+'}'for i in s.split('}') if i]

Solution 3:

You should use str.split('}') https://www.w3schools.com/python/ref_string_split.asp

I would do it this way :

string = '(->{200}o^{90}->{200}o^{90}->{200}o^{90}!0->{200}o^{90})'# remove the '(  )''string = string[1:-1]
# split the string
split_string = string.split('}')
# put back the '}''
split_string = [s + '}'for s in split_string if s is not '']
print(split_string)

Solution 4:

You can loop through the text and grab each character to make your own string, plus a comma and space when you encounter a }.

text = "(->{200}o^{90}->{200}o^{90}->{200}o^{90}!0->{200}o^{90})"
my_string = ""

forcharacterin text:
    my_string +=character
    if character== "}": my_string += ", "

This can be achieved in one line by using the join method too.

text = "(->{200}o^{90}->{200}o^{90}->{200}o^{90}!0->{200}o^{90})"my_string = "".join(c + (", " if c == "}" else "") for c in text)

Then you just need to remove the extra ", ".

Post a Comment for "How Do I Get Python To Detect A Right Brace, And Put A Space After That?"