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

Question:

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.

Asked By: Ufoguy

||

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]
Answered By: ShinTakezou

Heres what the simple function would look like:

def firstTwo(string):
    return string[:2]
Answered By: andyzinsser

For completeness: Instead of using def you could give a name to a lambda function:

first2 = lambda s: s[:2]
Answered By: Thorsten Kranz

In general, you can get the characters of a string from i until j with string[i:j].

string[:2] is shorthand for string[0:2]. This works for lists as well.

Learn about Python’s slice notation at the official tutorial

Answered By: stewSquared

In python strings are list of characters, but they are not explicitly list type, just list-like (i.e. it can be treated like a list). More formally, they’re known as sequence (see http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange):

>>> a = 'foo bar'
>>> isinstance(a, list)
False
>>> isinstance(a, str)
True

Since strings are sequence, you can use slicing to access parts of the list, denoted by list[start_index:end_index] see Explain Python's slice notation . For example:

>>> a = [1,2,3,4]
>>> a[0]
1 # first element, NOT a sequence.
>>> a[0:1]
[1] # a slice from first to second, a list, i.e. a sequence.
>>> a[0:2]
[1, 2]
>>> a[:2]
[1, 2]

>>> x = "foo bar"
>>> x[0:2]
'fo'
>>> x[:2]
'fo'

When undefined, the slice notation takes the starting position as the 0, and end position as len(sequence).

In the olden C days, it’s an array of characters, the whole issue of dynamic vs static list sounds like legend now, see Python List vs. Array – when to use?

Answered By: alvas

All previous examples will raise an exception in case your string is not long enough.

Another approach is to use
'yourstring'.ljust(100)[:100].strip().

This will give you first 100 chars.
You might get a shorter string in case your string last chars are spaces.

Answered By: Julien Kieffer
t = "your string"

Play with the first N characters of a string with

def firstN(s, n=2):
    return s[:n]

which is by default equivalent to

t[:2]
Answered By: J. Doe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.