Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another capitalise every odd char of the string solution

Tags:

python

string

I just started studying Python and created some kind of task for myself that I'm struggling to solve...

So, I'm on chapter on working with strings (accessing strings by index, changing etc).

My task is - capitalize every odd char of the string. I saw the solution here: Capitalise every other letter in a string in Python?

but I don't like it... wanted to solve this by slices. So what I produced is followig code:

T = 'somesampletexthere'  
R=""

for i in range(0, len(T[1::2])):
        R+=T[::2][i].upper()+T[1::2][i].lower()

print R

This code works great when there are even number of chars, for example with TESTTEXT but when the number is odd like here in EXAMPLE it will skipp last char (in this case E)

This is because the range is till len(T[1::2])) (length of even characters) but if I'll try the length of odd characters len(T[::2])) I'll get error:

IndexError: string index out of range

logically because number of odd chars will always be bigger on 1 (in case of text with odd number of characters).

So, my question is - how can I supress the error? So Python just return null or something in case the index is out of range of the given string?

Or any other solutions of the task using slices?

like image 727
Akhiles Avatar asked Feb 05 '23 19:02

Akhiles


1 Answers

You could just use enumerate and test for odd and even indices using a ternary operator. Then use join to join the string:

>>> T = 'somesampletexthere'
>>> ''.join(x.upper() if i%2 else x.lower() for i, x in enumerate(T))
'sOmEsAmPlEtExThErE'

You could handle whitespaces by using an external counter object provided by itertools.count:

>>> from itertools import count
>>> c = count()
>>> T = 'some sample text here'
>>> ''.join(x if x.isspace() else (x.upper() if next(c)%2 else x.lower()) for x in T)
'sOmE sAmPlE tExT hErE'
like image 106
Moses Koledoye Avatar answered Feb 08 '23 14:02

Moses Koledoye