python string character at index code example
Example 1: python string indexing
str = 'codegrepper'
# str[start:end:step]
#by default: start = 0, end = len(str), step = 1
print(str[:]) #codegrepper
print(str[::]) #codegrepper
print(str[5:]) #repper
print(str[:8]) #codegrep
print(str[::2]) #cdgepr
print(str[2:8]) #degrep
print(str[2:8:2]) #dge
#step < 0 : reverse
print(str[::-1]) #reppergedoc
print(str[::-3]) #rpgo
# str[start:end:-1] means start from the end, go backward and stop at start
print(str[8:3:-1]) #pperg
Example 2: python string indexof
s = "mouse"
animal_letter = s.find('s')
print animal_letter
Example 3: python char at
>>> s = "python"
>>> s[3]
'h'
>>> s[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[0]
'p'
>>> s[-1]
'n'
>>> s[-6]
'p'
>>> s[-7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>>
Example 4: how to get any letter of a string python
Random = "Whatever"#you can put anything here
words2 = Random.split(" ")
print('number of letters:')#you can delete this line...
print(len(Random))#and this one. these lines just Tell you how many
#letters there are
while True:#you can get rid of this loop if you want
ask = int(input("what letter do you want?"))
print(Random[ask-1])