0

Hey guys, is there any alternative methods to string slicing?

An example output would be:

input: dani
output:
d
da
dan
dani

I did this with string slicing, but am wondering if it is possible to do the same thing without slicing.

Anyone help out?

Testie,

3
Contributors
7
Replies
8
Views
7 Years
Discussion Span
Last Post by pyTony
0

You can print the characters one by one. Post your code, I'll post mine :)

Hi,

This is how I did it with string splicing.

def sequenceprint(s):
    """Prints out the input string in succession"""
    i = 0
    while i < len(s):
        print s[0:i+1]
        i = i + 1

However, I cannot do the same without the use of string slicing. Can you point me in the right direction?

Cheers,
Testie

0

Here is my code. It doesn't work without importing the future print_function.

# python 2 and 3
from __future__ import print_function

def sequenceprint2(s):
    for i in range(len(s)):
        for j in range(i):
            print(s[j], end='')
        print(s[i])

print("-"*10)
sequenceprint2("dani")
print("-"*10)

""" my output -->
----------
d
da
dan
dani
----------
"""

Edited by Gribouillis: n/a

0
def sequenceprint(s):
    """Prints out the input string in succession"""
    i = 0
    while i < len(s):
        print s[0:i+1]
        i = i + 1
0

Here is my code. It doesn't work without importing the future print_function.

# python 2 and 3
from __future__ import print_function

def sequenceprint2(s):
    for i in range(len(s)):
        for j in range(i):
            print(s[j], end='')
        print(s[i])

print("-"*10)
sequenceprint2("dani")
print("-"*10)

""" my output -->
----------
d
da
dan
dani
----------
"""

Hi,

Thanks for the help. But I'm wondering why the import is necessary. Also, I am wondering what

end=' '

does.

Cheers,
Testie

0

Hi,

Thanks for the help. But I'm wondering why the import is necessary. Also, I am wondering what

end=' '

does.

Cheers,
Testie

In python 2, the print statement print 'a', 'b' prints a space between a and b. To learn about python 3's print function (and the meaning of the sep argument), read this http://docs.python.org/py3k/library/functions.html?highlight=builtin%20functions#print

Note that you can't use the print statement and the print function in the same file, and also that imports from __future__ must come before any other statement in the file. In python 3 there is no print statement.

Edited by Gribouillis: n/a

0

Older style alternative is here with my code for non-slice and slice versions:

import sys
word = raw_input('Word: ')
for i in range(len(word)):
    for j in range(i+1):
        sys.stdout.write(word[j])
    print
print '-'*40
print '\n'.join(word[:i+1] for i in range(len(word)))
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.