问题:如何在Python中获取字符串的子字符串?

有没有一种方法可以在Python中为字符串加上字符串,以从第三个字符到字符串的末尾获取新的字符串?

也许喜欢myString[2:end]吗?

如果离开第二部分意味着“直到最后”,而如果离开第一部分,它是否从头开始?

Is there a way to substring a string in Python, to get a new string from the third character to the end of the string?

Maybe like myString[2:end]?

If leaving the second part means ’till the end’, and if you leave the first part, does it start from the start?


回答 0

>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'

Python称这个概念为“切片”,它不仅适用于字符串,还适用于更多的领域。看看这里的一个全面的介绍。

>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'

Python calls this concept “slicing” and it works on more than just strings. Take a look here for a comprehensive introduction.


回答 1

只是为了完整性,没有其他人提到过它。数组切片的第三个参数是一个步骤。因此,反转字符串很简单:

some_string[::-1]

或选择其他字符为:

"H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World"

在字符串中前进和后退的能力保持了从头到尾排列切片的一致性。

Just for completeness as nobody else has mentioned it. The third parameter to an array slice is a step. So reversing a string is as simple as:

some_string[::-1]

Or selecting alternate characters would be:

"H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World"

The ability to step forwards and backwards through the string maintains consistency with being able to array slice from the start or end.


回答 2

Substr()通常(即PHP和Perl)以这种方式工作:

s = Substr(s, beginning, LENGTH)

因此参数为beginningLENGTH

但是Python的行为是不同的。它期望从开始到结束(!)。初学者很难发现这一点。因此,正确替换Substr(s,Beginning,LENGTH)是

s = s[ beginning : beginning + LENGTH]

Substr() normally (i.e. PHP and Perl) works this way:

s = Substr(s, beginning, LENGTH)

So the parameters are beginning and LENGTH.

But Python’s behaviour is different; it expects beginning and one after END (!). This is difficult to spot by beginners. So the correct replacement for Substr(s, beginning, LENGTH) is

s = s[ beginning : beginning + LENGTH]

回答 3

实现此目的的一种常见方法是通过字符串切片。

MyString[a:b] 给您一个从索引a到(b-1)的子字符串。

A common way to achieve this is by string slicing.

MyString[a:b] gives you a substring from index a to (b – 1).


回答 4

这里似乎缺少一个示例:完整(浅)副本。

>>> x = "Hello World!"
>>> x
'Hello World!'
>>> x[:]
'Hello World!'
>>> x==x[:]
True
>>>

这是用于创建序列类型(而非插入字符串)的副本的常见用法[:]。浅表复制列表,请参阅无明显原因的Python列表切片语法

One example seems to be missing here: full (shallow) copy.

>>> x = "Hello World!"
>>> x
'Hello World!'
>>> x[:]
'Hello World!'
>>> x==x[:]
True
>>>

This is a common idiom for creating a copy of sequence types (not of interned strings), [:]. Shallow copies a list, see Python list slice syntax used for no obvious reason.


回答 5

有没有一种方法可以在Python中为字符串加上字符串,以从第3个字符到字符串的末尾获取新的字符串?

也许喜欢myString[2:end]吗?

是的,如果您将名称()分配或绑定end到常量单例,这实际上是可行的None

>>> end = None
>>> myString = '1234567890'
>>> myString[2:end]
'34567890'

切片符号具有3个重要参数:

  • 开始

如果未指定,则默认为None-但我们可以显式传递它们:

>>> stop = step = None
>>> start = 2
>>> myString[start:stop:step]
'34567890'

如果离开第二部分意味着“直到最后”,那么如果离开第一部分,它是否从头开始?

是的,例如:

>>> start = None
>>> stop = 2
>>> myString[start:stop:step]
'12'

请注意,我们在切片中包括了开始,但是我们仅上至(不包括)停止。

当step为时None,默认情况下切片将1用于该步骤。如果您使用负整数执行操作,则Python足够聪明,可以从头到尾进行操作。

>>> myString[::-1]
'0987654321'

我在对“解释切片符号问题”的回答中会详细解释切片符号。

Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?

Maybe like myString[2:end]?

Yes, this actually works if you assign, or bind, the name,end, to constant singleton, None:

>>> end = None
>>> myString = '1234567890'
>>> myString[2:end]
'34567890'

Slice notation has 3 important arguments:

  • start
  • stop
  • step

Their defaults when not given are None – but we can pass them explicitly:

>>> stop = step = None
>>> start = 2
>>> myString[start:stop:step]
'34567890'

If leaving the second part means ’till the end’, if you leave the first part, does it start from the start?

Yes, for example:

>>> start = None
>>> stop = 2
>>> myString[start:stop:step]
'12'

Note that we include start in the slice, but we only go up to, and not including, stop.

When step is None, by default the slice uses 1 for the step. If you step with a negative integer, Python is smart enough to go from the end to the beginning.

>>> myString[::-1]
'0987654321'

I explain slice notation in great detail in my answer to Explain slice notation Question.


回答 6

除了“结束”之外,您已经准备就绪。这称为切片符号。您的示例应为:

new_sub_string = myString[2:]

如果省略第二个参数,则它隐式为字符串的结尾。

You’ve got it right there except for “end”. It’s called slice notation. Your example should read:

new_sub_string = myString[2:]

If you leave out the second parameter it is implicitly the end of the string.


回答 7

我想在讨论中添加两点:

  1. 您可以None改为在空白处使用“从头开始”或“到末尾”来指定:

    'abcde'[2:None] == 'abcde'[2:] == 'cde'

    这在不能提供空格作为参数的函数中特别有用:

    def substring(s, start, end):
        """Remove `start` characters from the beginning and `end` 
        characters from the end of string `s`.
    
        Examples
        --------
        >>> substring('abcde', 0, 3)
        'abc'
        >>> substring('abcde', 1, None)
        'bcde'
        """
        return s[start:end]
  2. Python具有切片对象:

    idx = slice(2, None)
    'abcde'[idx] == 'abcde'[2:] == 'cde'

I would like to add two points to the discussion:

  1. You can use None instead on an empty space to specify “from the start” or “to the end”:

    'abcde'[2:None] == 'abcde'[2:] == 'cde'
    

    This is particularly helpful in functions, where you can’t provide an empty space as an argument:

    def substring(s, start, end):
        """Remove `start` characters from the beginning and `end` 
        characters from the end of string `s`.
    
        Examples
        --------
        >>> substring('abcde', 0, 3)
        'abc'
        >>> substring('abcde', 1, None)
        'bcde'
        """
        return s[start:end]
    
  2. Python has slice objects:

    idx = slice(2, None)
    'abcde'[idx] == 'abcde'[2:] == 'cde'
    

回答 8

如果myString包含以偏移量6开始且长度为9的帐号,则可以通过以下方式提取该帐号: acct = myString[6:][:9]

如果OP接受,他们可能想尝试一下,

myString[2:][:999999]

它可以正常工作-不会引发任何错误,也不会发生默认的“字符串填充”。

If myString contains an account number that begins at offset 6 and has length 9, then you can extract the account number this way: acct = myString[6:][:9].

If the OP accepts that, they might want to try, in an experimental fashion,

myString[2:][:999999]

It works – no error is raised, and no default ‘string padding’ occurs.


回答 9

也许我错过了,但是在此页面上找不到原始问题的完整答案,因为这里没有进一步讨论变量。所以我不得不继续寻找。

由于尚未允许我发表评论,因此让我在这里添加我的结论。我确定访问此页面时,我不是唯一对此感兴趣的人:

 >>>myString = 'Hello World'
 >>>end = 5

 >>>myString[2:end]
 'llo'

如果您离开第一部分,您会得到

 >>>myString[:end]
 'Hello' 

如果在中间也留下了:,则会得到最简单的子字符串,它是第5个字符(计数从0开始,因此在这种情况下为空白):

 >>>myString[end]
 ' '

Maybe I missed it, but I couldn’t find a complete answer on this page to the original question(s) because variables are not further discussed here. So I had to go on searching.

Since I’m not yet allowed to comment, let me add my conclusion here. I’m sure I was not the only one interested in it when accessing this page:

 >>>myString = 'Hello World'
 >>>end = 5

 >>>myString[2:end]
 'llo'

If you leave the first part, you get

 >>>myString[:end]
 'Hello' 

And if you left the : in the middle as well you got the simplest substring, which would be the 5th character (count starting with 0, so it’s the blank in this case):

 >>>myString[end]
 ' '

回答 10

好吧,我遇到了需要将PHP脚本转换为Python的情况,并且它有许多用法substr(string, beginning, LENGTH)
如果选择Python,string[beginning:end]则必须计算大量的结束索引,因此更简单的方法是使用string[beginning:][:length],这为我省去了很多麻烦。

Well, I got a situation where I needed to translate a PHP script to Python, and it had many usages of substr(string, beginning, LENGTH).
If I chose Python’s string[beginning:end] I’d have to calculate a lot of end indexes, so the easier way was to use string[beginning:][:length], it saved me a lot of trouble.


回答 11

使用硬编码的索引本身可能是一团糟。

为了避免这种情况,Python提供了一个内置对象slice()

string = "my company has 1000$ on profit, but I lost 500$ gambling."

如果我们想知道我剩下多少钱。

正常解决方案:

final = int(string[15:19]) - int(string[43:46])
print(final)
>>>500

使用切片:

EARNINGS = slice(15, 19)
LOSSES = slice(43, 46)
final = int(string[EARNINGS]) - int(string[LOSSES])
print(final)
>>>500

使用切片可以获得可读性。

Using hardcoded indexes itself can be a mess.

In order to avoid that, Python offers a built-in object slice().

string = "my company has 1000$ on profit, but I lost 500$ gambling."

If we want to know how many money I got left.

Normal solution:

final = int(string[15:19]) - int(string[43:46])
print(final)
>>>500

Using slices:

EARNINGS = slice(15, 19)
LOSSES = slice(43, 46)
final = int(string[EARNINGS]) - int(string[LOSSES])
print(final)
>>>500

Using slice you gain readability.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。