0

我有一个字符串:

"apples = green"

如何打印:

  1. 打印'='之前的所有内容(苹果)

  2. 打印'='之后的所有内容(绿色)

  3. 在文本文件中指定字符串的编号。我有 .txt 文件,其中包含:

    apples = green
    lemons = yellow
    ... = ...
    ... = ...
    
4

2 回答 2

6
  1. 使用分割字符串.split()

    print astring.split(' = ', 1)[0]
    
  2. 仍然使用以下方法拆分字符串.split()

    print astring.split(' = ', 1)[1]
    

    或者,您可以使用以下.partition()方法

    >>> astring = "apples = green"
    >>> print astring.split(' = ', 1)
    ['apples', 'green']
    >>> print astring.partition(' = ')
    ('apples', ' = ', 'green')
    

    分区总是只拆分一次,但也会返回您拆分的字符。

  3. 如果您需要读取文件中的特定行,请先通过遍历文件对象来跳过行。该itertools.islice()函数是返回该行的最紧凑的方式;如果您不了解这一切是如何运作的,请不要太担心。如果文件没有那么多行,则返回一个空字符串:

    from itertools import islice
    
    def read_specific_line(filename, lineno):
        with open(filename) as f:
            return next(islice(f, lineno, lineno + 1), '')
    

    从文件中读取第三行:

    line = read_specific_line('/path/to/some/file.txt', 3)
    

    相反,如果您需要知道给定文本的行号,则需要使用enumerate()来跟踪到目前为止的行数:

    def what_line(filename, text):
        with open(filename) as f:
            for lineno, line in enumerate(f):
                if line.strip() == text:
                    return lineno
        return -1
    

    这将返回行号(从 0 开始计数),如果在文件中找不到该行,则返回 -1。

于 2013-04-14T17:40:31.273 回答
1

python 中的每个字符串都有一个名为“split”的函数。如果您调用 string.split("substring") 它会创建一个列表,该列表完全符合您的要求。

>>> string = "apples = green"
>>> string.split("=")
['apples ', ' green']
>>> string = "apples = green = leaves = chloroplasts"
>>> string.split("=")
['apples ', ' green ', ' leaves ', ' chloroplasts']

所以,如果你使用 string.split(),你可以调用结果列表中的索引来获取你想要的子字符串:

>>> string.split(" = ")[0]
'apples'
>>> string.split(" = ")[1]
'green'
>>> string.split(" = ")[2]
'leaves'

等等...只要确保你有一个实际包含子字符串的字符串,否则对于任何大于 0 的索引都会引发 IndexError。

于 2013-04-14T17:47:07.690 回答