Forum Archive

Substitute for slice function

Wumfa150

I'm new to python and the iOS app but I have an application requirement.
I want I extract a single character from a string and have been led to understand I need to use the slice function, ie string[a:b] but after a quick search I find it can not be done in the iOS app.
Apologies if this has been covered but I wasn't sure how to search the forum for this.
Thanks in advance

eliskan175

This can definitely be done in Pythonista, I just tested it myself to make sure because if it didn't work that would be a big problem for me.

Probably you were setting up your string wrong, or accessing it improperly. Here's a solution that does work, test it in Pythonista and you will see!:

test = "Blahblahblah"
print test[:4]
print test[4:8]

The output should be simply "Blah", followed by a second "blah"

Another way you can access individual characters of a string is like this:

test="Blahblahblah"
for s in test: print s

This example prints each letter individually.

Another example to help you with string manipulation.. if you're looking for a specific WORD inside a string, you can use this:

test = "Just a string with a word we want. In this case, rainbows."
if "rainbows" in test: print "Our string has rainbows in it!"
if "nachos" in test: print "Share some nachos with me."

You can combine these functions together to get more control:

for index, s in enumerate(test):
if s=="h": print test[:index+1]

This example outputs:

Blah
Blahblah
Blahblahblah

I hope this helped.

Wumfa150

Thanks for the help. Your code worked fine. I must be writing the script incorrectly-

print "start..."
testword = "abcdefghijklmnop"
partstring = testword[3:3]
print "testword is "+testword
print "partstring is "+testword[3:3]
print partstring
print ("got:"+partstring+ " from "+testword)
print "done"

Gives me the following (including the blank 4th line)-

start...
testword is abcdefghijklmnop
partstring is

got: from abcdefghijklmnop
done

As I said, total newbie, so thanks for your patience with me

Wumfa150

Think I've just found my fix.
Having been learning lua simultaneously as python I have been referencing as string[start:length] where I should be using string[start:end] not realising that if start and end are the same it is null.
Apologies for my dumbness