1

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

Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177

3 Answers3

4

You might want to use string splicing (check out Aaron's Hall's question and the answers for a fantastic rundown on splice notation). What you're trying to do is splice the string from the first character to the end, like this: a[start:].

It looks like what you might be trying to do is the following:

while len(content) > 0:
    func(content)
    content = content[1:]
Community
  • 1
  • 1
Razi Shaban
  • 492
  • 1
  • 6
  • 17
2
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']
smac89
  • 39,374
  • 15
  • 132
  • 179
1

There are no views for strings in current versions of Python, so copying strings is unavoidable. 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
Apalala
  • 9,017
  • 3
  • 30
  • 48