如何在 Python 中获取字符串的前 2 个字母?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20988835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the first 2 letters of a string in Python?
提问by Ufoguy
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.
我如何获得这些字符串的前两个字母。为此,我需要 first2 函数。
采纳答案by ShinTakezou
It is as simple as string[:2]. A functioncan be easily written to do it, if you need.
就这么简单string[:2]。如果需要,可以轻松编写一个函数来执行此操作。
Even this, is as simple as
即使这样,也很简单
def first2(s):
return s[:2]
回答by andyzinsser
Heres what the simple function would look like:
下面是简单函数的样子:
def firstTwo(string):
return string[:2]
回答by Thorsten Kranz
For completeness: Instead of using defyou could give a name to a lambdafunction:
为了完整起见:def您可以为lambda函数命名,而不是使用:
first2 = lambda s: s[:2]
回答by stewSquared
In general, you can the characters of a string from iuntil jwith string[i:j].
string[:2]is shorthand for string[0:2]. This works for arrays as well.
在一般情况下,您可以将字符串从字符i,直到j用string[i:j]。
string[:2]是 的简写string[0:2]。这也适用于数组。
Learn about python's slice notation at the official tutorial
回答by alvas
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):
在 python 中字符串是字符列表,但它们不是明确的列表类型,只是类似列表(即它可以像列表一样对待)。更正式地,它们被称为sequence(参见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 slicingto access parts of the list, denoted by list[start_index:end_index]see Explain Python's slice notation. For example:
由于字符串是序列,因此您可以使用slicing访问列表的一部分,由list[start_index:end_index]参见解释 Python 的切片符号表示。例如:
>>> 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).
未定义时,切片符号将起始位置作为 0,结束位置作为 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?
在过去的 C 时代,它是一个字符数组,动态列表与静态列表的整个问题现在听起来像是传说,请参阅Python 列表与数组 - 何时使用?
回答by Julien Kieffer
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().
另一种方法是使用
'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.
这将为您提供前 100 个字符。如果您的字符串最后一个字符是空格,您可能会得到一个较短的字符串。
回答by J. Doe
t = "your string"
Play with the first N characters of a string with
播放字符串的前 N 个字符
def firstN(s, n=2):
return s[:n]
which is by defaultequivalent to
这是默认相当于
t[:2]

