是否有一种简单的方法可以迭代删除某个范围内字符串的每个开头字母?所以我想这样做:
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))
#...
我该怎么做到这一点?所以该功能可以在
上运行func(okay)
func(kay)
func(ay)
按顺序
答案 0 :(得分:4)
您可能希望使用字符串拼接(请查看Aaron's Hall's question and the answers以获得拼接表示法的精彩纲要)。你要做的是将字符串从第一个字符拼接到结尾,如下所示:a[start:]
。
您可能会尝试执行以下操作:
while len(content) > 0:
func(content)
content = content[1:]
答案 1 :(得分:2)
return [string[1:] for string in content]
示例:强>
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']
答案 2 :(得分:1)
当前版本的Python中没有字符串视图,因此复制字符串是不可避免的。你可以做些什么来避免同时在内存中保留所有后缀是使用生成器函数或返回生成器表达式的函数:
# -*- 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