0

I need to print [something] only one time, even if exactly the same string occurs next time. I tried this:

msg = "[something]" + random.randint(1,5)*str(random.randint(1,1000000000)) + "[something]"
i = msg[msg.index('['):msg.rindex(']')+1]
print i

but it works wrong. Message is prints up to last "]", I would like it to be up to the first "]". Between two "[something]" is randomly amount of strings. Is it posible with this code?

1
  • This might help: i = msg[msg.index('['):msg.index(']')+1] Commented Aug 23, 2015 at 13:25

2 Answers 2

2

Here are two ways you could do it:

import re

msg = "[something]" + random.randint(1,5)*str(random.randint(1,1000000000)) + "[something]"

print msg[msg.index('['):msg.index(']')+1]
print re.search("(\[.*?\])", msg).group(1)

Which will display:

[something]
[something]
Sign up to request clarification or add additional context in comments.

Comments

1

Use msg.index(']') instead of msg.rindex(']') as the last method searches "]" from the end of the string. For more details, see the doc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.