如何删除字符串的左侧部分?

gri*_*yvp 128 python string

我有一些简单的python代码搜索文件中的字符串,例如path=c:\path,c:\path可能会有所不同.目前的代码是:

def find_path(i_file):
    lines = open(i_file).readlines()
    for line in lines:
        if line.startswith("Path="):
            return # what to do here in order to get line content after "Path=" ?
Run Code Online (Sandbox Code Playgroud)

之后获取字符串文本的简单方法是什么Path=?有没有简单的方法,没有封闭,反射或其他深奥的东西?

MrT*_*opf 188

如果字符串是固定的,您可以简单地使用:

if line.startswith("Path="):
    return line[5:]
Run Code Online (Sandbox Code Playgroud)

它提供了从字符串中的位置5开始的所有内容(字符串也是一个序列,所以这些序列操作符也在这里工作).

或者您可以在第一行拆分=:

if "=" in line:
    param, value = line.split("=",1)
Run Code Online (Sandbox Code Playgroud)

然后param是"Path",值是第一个=后的其余部分.

  • 就像Dan Olson所说的那样,如果分隔符不存在,`split`会抛出异常.`partition`更稳定,它也分割一个字符串,*always*返回一个带有pre,delimiter和post-content的三元素元组(如果分隔符不存在,其中一些可能是'''`).例如,`value = line.partition('=')`. (6认同)
  • 分割方法的+1,避免了len(前缀)上手动切片的轻微丑陋. (2认同)

jfs*_*jfs 115

从字符串中删除前缀

# ...
if line.startswith(prefix):
   return line[len(prefix):]
Run Code Online (Sandbox Code Playgroud)

在第一次出现分隔符时分割 str.partition()

def findvar(filename, varname="Path", sep="=") :
    for line in open(filename):
        if line.startswith(varname + sep):
           head, sep_, tail = line.partition(sep) # instead of `str.split()`
           assert head == varname
           assert sep_ == sep
           return tail
Run Code Online (Sandbox Code Playgroud)

使用ConfigParser解析类似INI的文件

from ConfigParser import SafeConfigParser
config = SafeConfigParser()
config.read(filename) # requires section headers to be present

path = config.get(section, 'path', raw=1) # case-insensitive, no interpolation
Run Code Online (Sandbox Code Playgroud)

其他选择


Xav*_*hot 63

从 开始Python 3.9,您可以使用removeprefix

'Path=helloworld'.removeprefix('Path=')
# 'helloworld'
Run Code Online (Sandbox Code Playgroud)


fre*_*rin 18

对于切片(有条件或无条件),我更喜欢同事最近建议的内容; 使用空字符串替换.更容易阅读代码,更少的代码(有时)和更少的指定错误字符数的风险.好; 我不使用Python,但在其他语言中我更喜欢这种方法:

rightmost = full_path.replace('Path=', '', 1)
Run Code Online (Sandbox Code Playgroud)

或者-跟进到这个主题的第一个注释-如果此只应如果行开始Path:

rightmost = re.compile('^Path=').sub('', full_path)
Run Code Online (Sandbox Code Playgroud)

上面提到的一些主要区别在于没有涉及"神奇数字"(5),也没有必要同时指定' 5' 字符串' Path=',换句话说,我更喜欢这种代码维护方法观点看法.

  • 这不符合以"Path ="开头的字符串的原始要求. (3认同)
  • 您可以仅用 `rightmost = re.sub('^Path=', '', fullPath)` 替换正则表达式代码。`compile()` 方法的目的是在重用编译后的对象时使事情更快,但由于在使用后将其丢弃,因此无论如何它在这里都不起作用。无论如何,通常不值得担心这种优化。 (2认同)

Dav*_*ter 18

def remove_prefix(text, prefix):
    return text[len(prefix):] if text.startswith(prefix) else text
Run Code Online (Sandbox Code Playgroud)

无法抗拒这一行.需要Python 2.5+.


Tho*_*ber 13

我更喜欢pop索引[-1]:

value = line.split("Path=", 1).pop()
Run Code Online (Sandbox Code Playgroud)

value = line.split("Path=", 1)[1]
param, value = line.split("Path=", 1)
Run Code Online (Sandbox Code Playgroud)

  • 没有“幻数”的不错选择。值得注意的是,这是可行的,因为已经对“ startswith”进行了测试,因此“ split”将在“之前”和“之后”之间进行除法。`split(“ Path =”,1)`更精确(如果前缀在字符串的后面出现),但是会重新引入一个幻数。 (2认同)

Joh*_*men 11

或者为什么不呢

if line.startswith(prefix):
    return line.replace(prefix, '', 1)
Run Code Online (Sandbox Code Playgroud)


bat*_*rat 6

我能想到的最简单的方法是切片:

def find_path(i_file): 
    lines = open(i_file).readlines() 
    for line in lines: 
        if line.startswith("Path=") : 
            return line[5:]
Run Code Online (Sandbox Code Playgroud)

关于切片符号的快速说明,它使用两个索引而不是通常的索引。第一个索引表示您想要包含在切片中的序列的第一个元素,最后一个索引是您想要包含在切片中的最后一个元素之后的索引。
例如:

sequence_obj[first_index:last_index]
Run Code Online (Sandbox Code Playgroud)

切片由所有的元素first_indexlast_index,包括first_index和不last_index。如果省略第一个索引,则默认为序列的开头。如果省略最后一个索引,则它包括序列中直到最后一个元素的所有元素。也允许负指数。使用 Google 了解有关该主题的更多信息。


riz*_*iza 5

>>> import re

>>> p = re.compile(r'path=(.*)', re.IGNORECASE)

>>> path = "path=c:\path"

>>> re.match(p, path).group(1)
'c:\\path'
Run Code Online (Sandbox Code Playgroud)

  • 1. 使用 `r''` 字符串作为 Windows 路径。2. `re.match()` 可能返回 None (2认同)

Flo*_*rse 5

怎么样..

>>> line = r'path=c:\path'
>>> line.partition('path=')
('', 'path=', 'c:\\path')
Run Code Online (Sandbox Code Playgroud)

这个三联体是头部,分离器和尾部.

  • 这并非在所有情况下都以同样的方式起作用。如果存在分隔符,则结果是第三项。否则,结果是第一项。 (2认同)

pR0*_*0Ps 5

这里还没有提到的另一个简单的单行:

value = line.split("Path=", 1)[-1]
Run Code Online (Sandbox Code Playgroud)

这也适用于各种边缘情况:

>>> print("prefixfoobar".split("foo", 1)[-1])
"bar"

>>> print("foofoobar".split("foo", 1)[-1])
"foobar"

>>> print("foobar".split("foo", 1)[-1])
"bar"

>>> print("bar".split("foo", 1)[-1])
"bar"

>>> print("".split("foo", 1)[-1])
""
Run Code Online (Sandbox Code Playgroud)