Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get char from string by index?

Tags:

python

string

Lets say I have a string that consists of x unknown chars. How could I get char nr. 13 or char nr. x-14?

like image 814
TheBW Avatar asked Jan 13 '12 09:01

TheBW


People also ask

How do you find the character of a string at an index?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do I extract a character from a string?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

Can you access a string by index?

Strings are ordered sequences of character data, 00:15 and the individual characters of a string can be accessed directly using that numerical index. String indexing in Python is zero-based, so the very first character in the string would have an index of 0 , 00:30 and the next would be 1 , and so on.

What is the character at index?

The Java String charAt(int index) method returns the character at the specified index in a string. The index value that we pass in this method should be between 0 and (length of string-1). For example: s. charAt(0) would return the first character of the string represented by instance s.


1 Answers

First make sure the required number is a valid index for the string from beginning or end , then you can simply use array subscript notation. use len(s) to get string length

>>> 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 >>>  
like image 177
DhruvPathak Avatar answered Oct 01 '22 02:10

DhruvPathak