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
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]
Source: Stackoverflow.com