Python:删除字符串中第一个字母之前的所有字符

7

经过仔细搜索,我找到了如何删除特定字母前面的所有字符,但是没有找到如何删除任意字母前面的字符。

我想把一个字符串从这个样子转换:

"             This is a sentence. #contains symbol and whitespace

转化为:

This is a sentence. #No symbols or whitespace

我尝试了下面的代码,但是像第一个示例这样的字符串仍然会出现。
for ch in ['\"', '[', ']', '*', '_', '-']:
     if ch in sen1:
         sen1 = sen1.replace(ch,"")

这个例子中,代码不能删除双引号,原因不明;而且也无法删除前导空格,因为它会删掉所有的空格。

提前感谢你的帮助。

6个回答

5

不仅仅是删除空格,在删除第一个字母前的任何字符时,可以这样做:

#s is your string
for i,x in enumerate(s):
    if x.isalpha()         #True if its a letter
    pos = i                   #first letter position
    break

new_str = s[pos:]

2
import re
s = "  sthis is a sentence"

r = re.compile(r'.*?([a-zA-Z].*)')

print r.findall(s)[0]

我发现你的正则表达式对我正在尝试做的事情非常有用。来自未来4年的感谢! :) - theabhinavdas

1

去除所有空格和标点符号:

>>> text.lstrip(string.punctuation + string.whitespace)
'This is a sentence. #contains symbol and whitespace'

或者,另一种方法是找到第一个 ASCII 字母字符。例如:
>>> pos = next(i for i, x in enumerate(text) if x in string.ascii_letters)
>>> text[pos:]
'This is a sentence. #contains symbol and whitespace'

0

这是一个非常基础的版本;即它使用Python初学者容易理解的语法。

your_string = "1324 $$ '!'     '' # this is a sentence."
while len(your_string) > 0 and your_string[0] not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
    your_string = your_string[1:]
print(your_string)

#prints "this is a sentence."

优点:简单,无需导入
缺点:如果您感觉使用列表推导式更舒适,则可以避免while循环。 此外,使用正则表达式可以使您要比较的字符串更简单。

0

删除第一个字母之前的所有内容。

import itertools as it


s = "      -  .] *    This is a sentence. #contains symbol and whitespace"
"".join(it.dropwhile(lambda x: not x.isalpha(), s))
# 'This is a sentence. #contains symbol and whitespace'

或者,迭代字符串并测试每个字符是否在黑名单中。如果为真,则剥离该字符,否则短路。

def lstrip(s, blacklist=" "):    
    for c in s:
        if c in blacklist:
            s = s.lstrip(c)
            continue
        return s

lstrip(s, blacklist='\"[]*_-. ')
# 'This is a sentence. #contains symbol and whitespace'

-1

您可以使用 re.sub

import re
text = "             This is a sentence. #contains symbol and whitespace"

re.sub("[^a-zA-Z]+", " ", text)

re.sub(匹配模式, 替换字符串, 要搜索的字符串)


这实际上是在字符串中删除所有非字母字符,而不仅仅是像帖子标题所要求的那样只删除到第一个字母。 - greg hor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接