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

Let's say I have a string

Str1 = "TN 81 NZ 0025" 
str2 = "DL 11C AA 1111"
two = first2(str1)
print(two)
>>>TN

How do I get the first two letters of these strings. I need the first2 function for this.

This question is related to python string python-2.7

The answer is


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]

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]

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.


to print first two letter of a string

str = "string"

print(str[0:2])


Heres what the simple function would look like:

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

In general, you can the characters of a string from i until j with string[i:j]. string[:2] is shorthand for string[0:2]. This works for arrays as well.

Learn about python's slice notation at the official tutorial


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?


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

first2 = lambda s: s[:2]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict