0

I want to print the code that is always in the next line to the message Your One-time Verification Code is:

An Example of the message is:

Your One-time Verification Code is:

366522

The output should be 366522

Which python string method can be used to receive this code?

Atom Store
  • 961
  • 1
  • 11
  • 35

3 Answers3

4

The .split or .rsplit method is one solution that can get you there:

s = """\
Your One-time Verification Code is:

366522\
"""

# Split on newline, and pass limit=1 so we stop after N=1 splits. Note that
# the split is performed from the end of the string, since we use rsplit.

print(s.rsplit('\n', 1)[-1])
# 366522

If you have more lines after the verification code, use .split instead:

s = """\
Your One-time Verification Code is:

366522

Testing, testing
1 2 3
"""

# Split on newline, and pass limit=3 so we stop after N=3 splits. Then grab
# the third element (the last line that we split)

print(s.split('\n', 3)[2])
# 366522
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
  • If the message contains more sentences, and I only want the next line after the ` Your One-time Verification Code is : ` – Atom Store Sep 21 '21 at 03:37
  • Hmm, in that case I wouldn't suggest `rsplit`. Using `split` with limit=3 and retrieving the 3rd element/line should get you the verification code – rv.kvetch Sep 21 '21 at 03:40
2

You can use string split method (link to docs). \n is a character, that specifies a newline, so you can use it to split the string.

code = your_string.split('/n')[1]
Cassiopea
  • 255
  • 7
  • 16
1

BY using the .split or .rsplit method

Vikas
  • 17
  • 4