47

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.

wjandrea
  • 23,210
  • 7
  • 49
  • 68
Ufoguy
  • 847
  • 3
  • 9
  • 14
  • 1
    In this case `str1.split()[0]` also works, and may make more sense if you also need the other fields. – U2EF1 Jan 08 '14 at 07:18
  • @U2EF1, no, it does... str[0] gives you the first character, you need str[:2] and split is necessary too. – alvas Jan 08 '14 at 07:21
  • @alvas `str1.split()[0]` and `str1[0]` are two very different pieces of code. – U2EF1 Jan 08 '14 at 07:55
  • 1
    but it does the same and achieves a single element. and then you need to join then up `"".join(str1.split()[:2])` is redundant if there is not double spacing and `str[:2]` achieves the same. – alvas Jan 08 '14 at 07:58
  • @alvas Who said `str1.split()[:2]`? U2EFI said `str1.split()[0]` – wjandrea Oct 29 '21 at 05:10

7 Answers7

90

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]
Pkarls
  • 37
  • 3
  • 18
ShinTakezou
  • 9,154
  • 27
  • 39
  • 6
    This one is the right way to grab the first two characters. You answered the OP just right, so upvote. However, I would never use a function for this. I prefer to make it explicit in the code without having to chase down functions for verification. As in `firsttwo = somestring[:2]` in-line in the main code – SDsolar Aug 19 '17 at 09:06
  • 1
    I agree, in fact I wrote “A function can be easily written to do it, if you need.” It wouldn't make sense to have tons of functions like `first2`, `first3`, `first4`… – ShinTakezou Aug 22 '17 at 19:39
11

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

wjandrea
  • 23,210
  • 7
  • 49
  • 68
stewSquared
  • 763
  • 4
  • 24
5
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]
J. Doe
  • 3,010
  • 2
  • 20
  • 37
4

Heres what the simple function would look like:

def firstTwo(string):
    return string[:2]
andyzinsser
  • 2,363
  • 2
  • 16
  • 17
3

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?

Community
  • 1
  • 1
alvas
  • 105,505
  • 99
  • 405
  • 683
1

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.

Julien Kieffer
  • 1,096
  • 6
  • 14
0

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

first2 = lambda s: s[:2]
Thorsten Kranz
  • 11,837
  • 1
  • 36
  • 53