Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first 2 letters of a string in Python?

Tags:

python

string

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.

like image 380
Ufoguy Avatar asked Jan 08 '14 06:01

Ufoguy


People also ask

How do you get the first two letters of a string in Python?

To extract the first two characters of a list in Python you can use [:2] which is the short version of [0:2].

How do you get the first two letters of a string?

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.


1 Answers

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] 
like image 196
ShinTakezou Avatar answered Sep 29 '22 23:09

ShinTakezou