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?
CodePudding user response:
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]
CodePudding user response:
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
CodePudding user response:
BY using the .split or .rsplit method