Dick Armstrong
Dick Armstrong

Reputation: 135

printing parts of a string while skipping others in Python

Say I have the following code:

myVariable = "goodmorning"

I can slice it with e.g. myVariable[1:2] (like Paolo Bergantino said here: Is there a way to substring a string in Python?), but how can I print some of the characters while jumping over others? e.g. how can I make it print "gdorn"? I tried myVariable[0,3,5,6,7] (which is wrong as it turns out) and I was thinking to myself that, if myVariable[0,3,5,6,7] worked then maybe myVariable[0,3,5:7] would work as well (I hope you see my reasoning), which it doesn't. I am learning Python through codecademy and I didn't cover functions yet, in case you go into functions and such so if there is something easier like what I tried then I would be appreciate it if you explain it!

Upvotes: 1

Views: 182

Answers (3)

geeves
geeves

Reputation: 661

It can be as simple as

myVariable = "goodmorning"
print (myVariable[0] + myVariable[3] + myVariable[5]  + myVariable[6] + myVariable[7] )

which outputs "gdorn".

It's not elegant. It simply builds up the string one substring at a time.

Upvotes: 0

kezzos
kezzos

Reputation: 3221

You could try

myVariable = 'iheoiahwd'
idxs = [0, 3, 4, 6, 7]

myVariable = [myVariable[i] for i in idxs] 
print ''.join(myVariable)

Or simplified to a one liner:

print ''.join([myVariable[i] for i in [0, 3, 4, 6, 7]])

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113930

my_indices = [1,2,5,6,9]
print "".join(x for i,x in enumerate(my_string) if i in my_indices)

is one way you could do this

you could also use numpy

print "".join(numpy.array(list(my_string))[my_indices])

this would let you do weird things like

my_indices = [1,2,3,4,9,9,8]

Upvotes: 0

Related Questions