56

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.

5
  • 1
    In this case str1.split()[0] also works, and may make more sense if you also need the other fields. Commented Jan 8, 2014 at 7:18
  • @U2EF1, no, it does... str[0] gives you the first character, you need str[:2] and split is necessary too. Commented Jan 8, 2014 at 7:21
  • @alvas str1.split()[0] and str1[0] are two very different pieces of code. Commented Jan 8, 2014 at 7: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. Commented Jan 8, 2014 at 7:58
  • @alvas Who said str1.split()[:2]? U2EFI said str1.split()[0] Commented Oct 29, 2021 at 5:10

7 Answers 7

114

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]
Sign up to request clarification or add additional context in comments.

2 Comments

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
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
16

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

Comments

7
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]

Comments

4

Heres what the simple function would look like:

def firstTwo(string):
    return string[:2]

Comments

4

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?

Comments

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.

1 Comment

Not true: e.g. ''[:2] just returns ''. No exception.
0

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

first2 = lambda s: s[:2]

1 Comment

Named lambdas are bad practice. Use a def instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.