user3423572
user3423572

Reputation: 559

Python 2.7: Select specific character from string

I'm trying to figure out how to select a specific character from a string. I know you can use the [0:0] and [0:-0] syntax etc... However I'm trying to do something different.

If a user enters "Hello, my name is [lol] bob [not[really]] john[son]" or enters "[[[[]]][[][][]"

I'm trying to count how many square brackets have been typed and either left or right.

Thanks a lot guys for the instant response, a lot of help!

Upvotes: 1

Views: 576

Answers (2)

Sabuj Hassan
Sabuj Hassan

Reputation: 39405

May be there have a better way, but it will do:

input = 'Hello, my name is [lol] bob [not[really]] john[son]'
print len(re.findall("\[|\]", input))

Upvotes: 0

Paulo Bu
Paulo Bu

Reputation: 29804

You can use str.count method if you only need to count them:

>>>s = "Hello, my name is [lol] bob [not[really]] john[son]"
>>>s.count('[') + s.count(']')
8

Upvotes: 3

Related Questions