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

彻底搜索后,我可以找到如何在特定字母之前删除所有字符,但不能在任何字母之前删除.

我试图从这里转一个字符串:

"             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,"")

由于某些未知原因,这不仅无法删除示例中的双引号,而且还无法删除前导空格,因为它会删除所有空格.

先感谢您.

最佳答案 不要只是删除空格,以便在第一个字母之前删除任何字符,请执行以下操作:

#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:]
点赞