Let's say I have a string
str1 = "TN 81 NZ 0025" two = first2(str1) print(two) # -> TN
How do I get the first two letters of this string? I need the first2
function for this.
To extract the first two characters of a list in Python you can use [:2] which is the short version of [0:2].
Use the String. substring() method to get the first two characters of a string, e.g. const first2 = str. substring(0, 2); . The substring method will return a new string containing the first two characters of the original string.
It is as simple as string[:2]
. A function can be easily written to do it, if you need.
Even this, is as simple as
def first2(s): return s[:2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With