John Paul Hayes
John Paul Hayes

Reputation: 798

Is it possible to determine if a string begins with an character repeating x times?

I have a two strings

code_one = "222abc"
code_two = "2abc"

Is there a way I can determine that strings begin with "2" repeating any number of times?

Upvotes: 0

Views: 80

Answers (2)

bReimers
bReimers

Reputation: 87

Assuming tests would include characters other than '2', perhaps grab character [0] and compare to [1] and if equal then lstrip on that character as shown to get a count (if needed )

Upvotes: 0

Chris_Rands
Chris_Rands

Reputation: 41168

You can simply use lstrip() and compare the lengths:

>>> code_one = "222abc"
>>> len(code_one) - len(code_one.lstrip("2"))
3

Or if you just want to check the string starts with some characters:

>>> code_one.startswith("222")
True

Upvotes: 8

Related Questions