简体   繁体   English

python3反复从字符串中删除第一个字符

[英]python3 iteratively remove first character from string

Is there an easy way to iteratively remove each beginning letter of a string in a range? 有没有一种简便的方法来迭代地删除范围中字符串的每个开头字母? so I want to do: 所以我想做:

for h in content:
  data = func(h) #returns list
  for i in range(0,len(h) - 1):
    tmp = h
    #remove first letter of string h
    data.append(func(tmp))
  #...

how can I accomplish this? 我该怎么做? so the function can be ran on say 所以功能可以说

func(okay)
func(kay)
func(ay)

in that order 以该顺序

You might want to use string splicing (check out Aaron's Hall's question and the answers for a fantastic rundown on splice notation). 您可能要使用字符串拼接(请查看Aaron's Hall的问题和答案以了解拼接符号的精简概述)。 What you're trying to do is splice the string from the first character to the end, like this: a[start:] . 您想要做的是将字符串从第一个字符到结尾进行拼接,如下所示: a[start:]

It looks like what you might be trying to do is the following: 您可能要尝试执行以下操作:

while len(content) > 0:
    func(content)
    content = content[1:]
return [string[1:] for string in content]

Example: 例:

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from itertools import permutations
>>> [string[1:] for string in ["".join(words) for words in permutations("Fig")]]
['ig', 'gi', 'Fg', 'gF', 'Fi', 'iF']

There are no views for strings in current versions of Python, so copying strings is unavoidable. 当前版本的Python中没有字符串视图,因此复制字符串是不可避免的。 What you can do to avoid keeping all suffixes in memory at the same time is to use a generator function, or a function that returns a generator expression: 为了避免将所有后缀同时保留在内存中,您可以做的是使用生成器函数或返回生成器表达式的函数:

# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals


def suffixes(s):
    for i in range(len(s)):
        yield s[i:]


def suffixes2(s):
    return (s[i:] for i in range(len(s)))


def func(s):
    print(s)


for s in suffixes('okay'):
    func(s)

for s in suffixes2('okay'):
    func(s)

okay
kay
ay
y
okay
kay
ay
y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM