programing tip

인덱스로 문자열에서 문자를 얻는 방법?

itbloger 2020. 10. 8. 07:46
반응형

인덱스로 문자열에서 문자를 얻는 방법?


x 개의 알 수없는 문자로 구성된 문자열이 있다고 가정 해 보겠습니다. 어떻게 char nr을 얻을 수 있습니까? 13 또는 char nr. x-14?


먼저 필요한 숫자가 시작 또는 끝의 문자열에 대한 유효한 인덱스 인지 확인한 다음 배열 첨자 표기법을 사용할 수 있습니다. len(s)문자열 길이를 얻는 데 사용

>>> 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
>>> 

In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45

이제 x에 대한 양수 인덱스 범위는 0에서 44까지입니다 (예 : 길이-1).

In [3]: x[0]
Out[3]: 'a'
In [4]: x[45]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

/home/<ipython console> in <module>()

IndexError: string index out of range

In [5]: x[44]
Out[5]: 's'

음수 인덱스의 경우 인덱스 범위는 -1에서 -45입니다.

In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a

음수 색인의 경우 음수 [길이 -1] 즉, 양수 색인의 마지막 유효한 값은 목록을 역순으로 읽을 때 두 번째 목록 요소를 제공합니다.

In [8]: x[-44]
Out[8]: 'n'

기타, 인덱스의 예,

In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'

이전 답변 ASCII character은 특정 색인 에 대해 다룹니다 .

Unicode characterPython 2에서 특정 인덱스 를 얻는 것은 약간 번거 롭습니다.

E.g., with s = '한국中国にっぽん' which is <type 'str'>,

__getitem__, e.g., s[i] , does not lead you to where you desire. It will spit out semething like . (Many Unicode characters are more than 1 byte but __getitem__ in Python 2 is incremented by 1 byte.)

In this Python 2 case, you can solve the problem by decoding:

s = '한국中国にっぽん'
s = s.decode('utf-8')
for i in range(len(s)):
    print s[i]

Python.org has an excellent section on strings here. Scroll down to where it says "slice notation".


Another recommended exersice for understanding lists and indexes:

L = ['a', 'b', 'c']
for index, item in enumerate(L):
    print index + '\n' + item

0
a
1
b
2
c 

This should further clarify the points:

a = int(raw_input('Enter the index'))
str1 = 'Example'
leng = len(str1)
if (a < (len-1)) and (a > (-len)):
    print str1[a]
else:
    print('Index overflow')

Input 3 Output m

Input -3 Output p

참고URL : https://stackoverflow.com/questions/8848294/how-to-get-char-from-string-by-index

반응형