Indexerror string index out of range как исправить

I'm currently learning python from a book called 'Python for the absolute beginner (third edition)'. There is an exercise in the book which outlines code for a hangman game. I followed along with t...

I’m currently learning python from a book called ‘Python for the absolute beginner (third edition)’. There is an exercise in the book which outlines code for a hangman game. I followed along with this code however I keep getting back an error in the middle of the program.

Here is the code that is causing the problem:

if guess in word:
    print("nYes!", guess, "is in the word!")

    # Create a new variable (so_far) to contain the guess
    new = ""
    i = 0
    for i in range(len(word)):
        if guess == word[i]:
            new += guess
        else:
            new += so_far[i]
        so_far = new

This is also the error it returns:

new += so_far[i]
IndexError: string index out of range

Could someone help me out with what is going wrong and what I can do to fix it?

edit: I initialised the so_far variable like so:

so_far = "-" * len(word)

asked Jan 3, 2012 at 12:58

Darkphenom's user avatar

DarkphenomDarkphenom

6472 gold badges8 silver badges14 bronze badges

2

It looks like you indented so_far = new too much. Try this:

if guess in word:
    print("nYes!", guess, "is in the word!")

    # Create a new variable (so_far) to contain the guess
    new = ""
    i = 0
    for i in range(len(word)):
        if guess == word[i]:
            new += guess
        else:
            new += so_far[i]
    so_far = new # unindented this

answered Jan 3, 2012 at 13:25

Rob Wouters's user avatar

Rob WoutersRob Wouters

15.4k3 gold badges40 silver badges36 bronze badges

1

You are iterating over one string (word), but then using the index into that to look up a character in so_far. There is no guarantee that these two strings have the same length.

answered Jan 3, 2012 at 13:00

unwind's user avatar

unwindunwind

387k64 gold badges468 silver badges600 bronze badges

This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like

so_far = " " * len(word)

?

Edit:

try something like

print "%d / %d" % (new, so_far)

before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you’re not actually using the instance you think.

answered Jan 3, 2012 at 13:02

CNeo's user avatar

CNeoCNeo

7061 gold badge6 silver badges10 bronze badges

3

There were several problems in your code.
Here you have a functional version you can analyze (Lets set ‘hello’ as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    print(so_far)
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
            else:
                new += so_far[i]    # same value as before
        so_far = new
    else:
        print("try_again")

print('finish')

I tried to write it for py3k with a py2k ide, be careful with errors.

answered Jan 3, 2012 at 13:33

joaquin's user avatar

joaquinjoaquin

81.1k28 gold badges137 silver badges151 bronze badges

1

In this Python tutorial, we will discuss how to handle indexerror: string index out of range in Python. We will check how to fix the error indexerror string index out of range python 3.

In python, an indexerror string index out of range python error occurs when a character is retrieved by an index that is outside the range of string value, and the string index starts from ” 0 “ to the total number of the string index values.

Example:

name = "Jack"
value = name[4]
print(value)

After writing the above code (string index out of range), Ones you will print “ value” then the error will appear as an “ IndexError: string index out of range ”. Here, index with name[4] is not in the range, so this error arises because the index value is not present and it is out of range.

You can refer to the below screenshot string index out of range

indexerror string index out of range python
IndexError: string index out of range

This is IndexError: string index out of range.

To solve this IndexError: string index out of range we need to give the string index in the range so that this error can be resolved. The index starts from 0 and ends with the number of characters in the string.

Example:

name = "Jack"
value = name[2]
print('The character is: ',value)

After writing the above code IndexError: string index out of range this is resolved by giving the string index in the range, Here, the index name[2] is in the range and it will give the output as ” The character is: c ” because the specified index value and the character is in the range.

You can refer to the below screenshot how to solve the IndexError: string index out of range.

indexerror string index out of range python 3

So, the IndexError is resolved string index out of range.

You may like following Python tutorials:

  • Unexpected EOF while parsing Python
  • Remove Unicode characters in python
  • Comment lines in Python
  • Python dictionary append with examples
  • Check if a list is empty in Python
  • Python Dictionary Methods + Examples
  • Python list methods
  • Python String Functions
  • syntaxerror invalid character in identifier python3
  • Remove character from string Python
  • What does the percent sign mean in python

This is how to solve IndexError: string index out of range in python or indexerror string index out of range python 3.

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Like lists, Python strings are indexed. This means each value in a string has its own index number which you can use to access that value. If you try to access an index value that does not exist in a string, you’ll encounter a “TypeError: string index out of range” error.

In this guide, we discuss what this error means and why it is raised. We walk through an example of this error in action to help you figure out how to solve it.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

TypeError: string index out of range

In Python, strings are indexed starting from 0. Take a look at the string “Pineapple”:

P i n e a p p l e
1 2 3 4 5 6 7 8

“Pineapple” contains nine letters. Because strings are indexed from 0, the last letter in our string has the index number 8. The first letter in our string has the index number 0.

If we try to access an item at position 9 in our list, we’ll encounter an error. This is because there is no letter at index position 9 for Python to read.

The “TypeError: string index out of range” error is common if you forget to take into account that strings are indexed from 0. It’s also common in for loops that use a range() statement.

Example Scenario: Strings Are Indexed From 0

Take a look at a program that prints out all of the letters in a string on a new line:

def print_string(sentence):
	count = 0

	while count <= len(sentence):
		print(sentence[count])
		count += 1

Our code uses a while loop to loop through every letter in the variable “sentence”. Each time a loop executes, our variable “count” is increased by 1. This lets us move on to the next letter when our loop continues.

Let’s call our function with an example sentence:

Our code returns:

S
t
r
i
n
g
Traceback (most recent call last):
  File "main.py", line 8, in <module>
	print_string("test")
  File "main.py", line 5, in print_string
	print(sentence[count])
IndexError: string index out of range

Our code prints out each character in our string. After every character is printed, an error is raised. This is because our while loop continues until “count” is no longer less than or equal to the length of “sentence”.

To solve this error, we must ensure our while loop only runs when “count” is less than the length of our string. This is because strings are indexed from 0 and the len() method returns the full length of a string. So, the length of “string” is 6. However, there is no character at index position 6 in our string.

Let’s revise our while loop:

while count < len(sentence):

This loop will only run while the value of “count” is less than the length of “sentence”.

Run our code and see what happens:

Our code runs successfully!

Example Scenario: Hamming Distance Program

Here, we write a program that calculates the Hamming Distance between two sequences. This tells us how many differences there are between two strings.

Start by defining a function that calculates the Hamming distance:

def hamming(a, b):
	differences = 0

	for c in range(0, len(a)):
		if a[c] != b[c]:
			differences += 1

	return differences

Our function accepts two arguments: a and b. These arguments contain the string values that we want to compare.

In our function, we use a for loop to go through each position in our strings to see if the characters at that position are the same. If they are not the same, the “differences” counter is increased by one.

Call our function and try it out with two strings:

answer = hamming("Tess1", "Test")
print(answer)

Run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
	answer = hamming("Tess1", "Test")
  File "main.py", line 5, in hamming
	if a[c] != b[c]:
IndexError: string index out of range

Our code returns an error. This is because “a” and “b” are not the same length. “a” has one more character than “b”. This causes our loop to try to find another character in “b” that does not exist even after we’ve searched through all the characters in “b”.

We can solve this error by first checking if our strings are valid:

def hamming(a, b):
	differences = 0

	if len(a) != len(b):
		print("Strings must be the same length.")
		return 

	for c in range(0, len(a)):
		if a[c] != b[c]:
			differences += 1

	return differences

We’ve used an “if” statement to check if our strings are the same length. If they are, our program will run. If they are not, our program will print a message to the console and our function will return a null value to our main program. Run our code again:

Strings must be the same length.
None

Our code no longer returns an error. Try our algorithm on strings that have the same length:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

answer = hamming("Test", "Tess")
print(answer)

Our code returns: 1. Our code has successfully calculated the Hamming Distance between the strings “Test” and “Tess”.

Conclusion

The “TypeError: string index out of range” error is raised when you try to access an item at an index position that does not exist. You solve this error by making sure that your code treats strings as if they are indexed from the position 0.

Now you’re ready to solve this common Python error like a professional coder!

The python error IndexError: string index out of range occurs if a character is not available at the string index. The string index value is out of range of the String length. The python error IndexError: string index out of range occurs when a character is retrieved from the out side index of the string range.

The IndexError: string index out of range error occurs when attempting to access a character using the index outside the string index range. To identify a character in the string, the string index is used. This error happens when access is outside of the string’s index range.

If the character is retrieved by an index that is outside the range of the string index value, the python interpreter can not locate the location of the memory. The string index starts from 0 to the total number of characters in the string. If the index is out of range, It throws the error IndexError: string index out of range.

A string is a sequence of characters. The characters are retrieved by the index. The index is a location identifier for the ordered memory location where character is stored. A string index starts from 0 to the total number of characters in the string.

Exception

The IndexError: string index out of range error will appear as in the stack trace below. Stack trace shows the line the error has occurred at.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    print ("the value is ", x[6])
IndexError: string index out of range
[Finished in 0.1s with exit code 1]

Root cause

The character in the string is retrieved via the character index. If the index is outside the range of the string index the python interpreter can’t find the character from the location of the memory. Thus it throws an error on the index. The string index starts from 0 and ends with the character number in the string.

Forward index of the string

Python allows two forms of indexing, forward indexing and backward indexing. The forward index begins at 0 and terminates with the number of characters in the string. The forward index is used to iterate a character in the forward direction. The character in the string will be written in the same index order.

Index 0 1 2 3 4
Value a b c d e

Backward index of the string

Python allows backward indexing. The reverse index starts from-1 and ends with the negative value of the number of characters in the string. The backward index is used to iterate the characters in the opposite direction. In the reverse sequence of the index, the character in the string is printed. The back index is as shown below

Index -5 -4 -3 -2 -1
Value a b c d e

Solution 1

The index value should be within the range of String. If the index value is out side the string index range, the index error will be thrown. Make sure that the index range is with in the index range of the string. 

The string index range starts with 0 and ends with the number of characters in the string. The reverse string index starts with -1 and ends with negative value of number of characters in the string.

In the example below, the string contains 5 characters “hello”. The index value starts at 0 and ends at 4. The reverse index starts at -1 and ends at -5.

Program

x = "hello"
print "the value is ", x[5]

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    print "the value is ", x[5]
IndexError: string index out of range
[Finished in 0.0s with exit code 1]

Solution

x = "hello"
print "the value is ", x[4]

Output

the value is  o
[Finished in 0.1s]

Solution 2

If the string is created dynamically, the string length is unknown. The string is iterated and the characters are retrieved based on the index. In this case , the value of the index is unpredictable. If an index is used to retrieve the character in the string, the index value should be validated with the length of the string.

The len() function in the string returns the total length of the string. The value of the index should be less than the total length of the string. The error IndexError: string index out of range will be thrown if the index value exceeds the number of characters in the string

Program

x = "hello"
index = 5
print "the value is ", x[index]

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    print "the value is ", x[index]
IndexError: string index out of range
[Finished in 0.1s with exit code 1]

Solution

x = "hello"
index = 4
if index < len(x) :
	print "the value is ", x[index]

Output

the value is  o
[Finished in 0.1s]

Solution 3

Alternatively, the IndexError: string index out of range error is handled using exception handling. The try block is used to handle if there is an index out of range error.

x = "hello"
print "the value is ", x[5]

Exception

the value is 
Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    print "the value is ", x[5]
IndexError: string index out of range
[Finished in 0.1s with exit code 1]

Solution

try:
	x = "hello"
	print "the value is ", x[5]
except:
	print "not available"

Output

the value is  not available
[Finished in 0.1s]

In this tutorial, we will discuss how to handle string index out of range error. Before moving ahead, let’s first understand what is string index out of range error is in Python.

Just like lists, strings are also indexed in Python. We can define a string as a set of Unicode characters stored inside. In simpler terms, you can access each item in a string using its index value which starts with zero. So the first character index is 0, and the last character index is equal to the length of the string-1.

Whenever you try to access an item whose index value does not exist in the string, an error is thrown by the Python interpreter known as string index out of range.

Also Read: Python For Loop Index With Examples

Let us consider a string: Codeitbro. In this string, the index of C is 0, and the index of o is 8 (as the length of the string is 9).

When accessing the characters inside a string, we can use their index values to access them. However, if you use an index not available in the string, you will get the index out of range error.

As in the above example, the index range is only up to 8. but if we try to access it using an index value of 10, we will get the error.

Let’s see the error in the below code to get a value at the 10th index position.

#consider a string
my_string = "Codeitbro"

#get the tenth charcater
print(my_string[9])

Error:

index out of range error in python

IndexError                                Traceback (most recent call last)
<ipython-input-22-5d6870b88bcc> in <module>()
      3 
      4 #get the tenth charcater
----> 5 print( my_string[9])
      6 

IndexError: string index out of range

Also Read: How to Reverse an Array In Python [Flip Array]

How to Handle String Index Out of Range Error In Python

To handle this error, we will see the following methods.

Method 1: Use the relevant index

We have to use the index of a character in the string only. To get the character by indexing from the string, you can use [].

Syntax:

my_string[index]

Where,

1. my_string is the input string.

2. index is the character index in the string that is present.

Also Read: How to Check If Dict Has Key in Python [5 Methods]

Example:

We will create a string and get the character using an index in this example.

#consider a string
my_string = "Codeitbro"

#get the first charcater
print( my_string[0])

#get the fifth charcater
print( my_string[4])

#get the second charcater
print( my_string[3])

#get the last charcater
print( my_string[8])

Output:

C
i
e
o

Also Read: How to Convert Binary to Decimal in Python [5 Methods]

Method 2: Using Exception Handling to Handle String Index Out of Range Error

We will use the exception handling concept to handle the error in this scenario. For this, we will use try and except code blocks.

Here’s the syntax:

try:
  statements

except IndexError:
  handling

In the try block, we will use statements to retrieve a value based on an index value in the string. If there is no error, it will return the character. Otherwise, Python will execute the statements in the except block to handle the error.

Also Read: Python Program To Display Fibonacci Series Up To N Terms

Let’s see a few examples to understand this more coherently.

Example 1: In this example, we will create a string and try to get the tenth character using index and display an error message if there is any string index out of range error under the except block.

Code:

#consider a string
my_string = "Codeitbro"

try:
  #get the tenth charcater
  print( my_string[9])

except IndexError:
  print("Index error occured")

Output:

Index error occured

Also Read: How To Automate Google Search With Python

Example 2: We will create a string and get the seventh character using the index in this example.

#consider a string
my_string = "Codeitbro"

try:
  #get the seventh charcater
  print( my_string[6])

except IndexError:
  print("Index error occured")

There is no error found in the try block of the above code, and therefore it prints the sixth character of the string, i.e., “b.”

Output:

b

Also Read: 10 Best Udemy Python Courses for Beginners

Wrapping Up

In this tutorial, we explored two methods to handle string index out of range error in Python. The first is pretty straightforward, in which you have to use the correct index to get a value from the string. The second method is robust as it uses the exception handling concept to handle the index out of range error.

Next Reads:

  • Learn Python Online With These 12 Best Free Websites
  • 7 Best Python IDE for Windows [Code Editors]
  • 11 Best Python Libraries for Machine Learning
  • How To Make A Simple Python 3 Calculator Using Functions
  • How To Create Keylogger In Python
  • How To Make A Digital Clock In Python Using Tkinter
  • Working With Python 3 Lists | Learn By Examples
  • Dictionary In Python 3 | Learn With Examples

Доброго времени суток!
Я новичок, пытаюсь написать программу, которая будет в строке находить повторяющиеся буквы, считать их количество подряд выводить что-то наподобие этого: s = ‘aaaabbсaa’ преобразуется в ‘a4b2с1a2’.
Но на выходе получаю ошибку IndexError: string index out of range. Ошибка возникает после использования цикла for in.
Прошу помощи, код прилагаю ниже.

genome = 'aaaabbcaa'
a = 1
s = 1
g = ''
for i in genome:
    if genome[a-1]==genome[a]:
        a += 1
        s += 1
    else:
        g += (genome[a-1]+str(s))
        a += 1
        s += 1
print(g)
----------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-176-241c9dc2be5a> in <module>
      4 g = ''
      5 for i in genome:
----> 6     if genome[a-1]==genome[a]:
      7         a += 1
      8         s += 1

IndexError: string index out of range


  • Вопрос задан

    более двух лет назад

  • 6012 просмотров

HelloDarknessMyOldFried, Я бы предложил

следующий код

genome = 'aaaabbcaa'
cnt = 0
res = ''
for i in range(len(genome)):
  newSymb = i == 0 or genome[i] != genome[i - 1]
  if newSymb:
      if cnt > 0: g += str(cnt)
      res += genome[i]
      cnt = 1
  else:
      cnt += 1
res += str(cnt)

print(res)

Мой вариант такой, в принципе вместо дека можно использовать и обычный list:

import collections
genome = 'aaaabbcaa'
result = collections.deque()
genome += '$'
last = genome[0]
counter = 1
for c in genome[1:]:
  if c == last:
    counter += 1
  else:
    result.append('%s%d' % (last, counter))
    last = c
    counter = 1
print(''.join(result))

Пригласить эксперта

Как вариант можете также можете рассмотреть мой вариант:

spoiler

genome = 'aaaabbcaa'
gn = list(genome)
arr = []
text = ''
ln = len(gn)
for i in range(ln):
	a = 0
	for j in range(ln-1):
		if gn[i] == gn[j+1]:
			a +=1	
	text = gn[i] + str(a)
	arr.append(text)

arr = ''.join(arr)
print (arr)

Останется сделать малое: убрать повторяющиеся элементы и что-то сделать с последними ‘aa’. Удачи!


  • Показать ещё
    Загружается…

09 февр. 2023, в 23:00

1500 руб./за проект

09 февр. 2023, в 22:06

500 руб./за проект

09 февр. 2023, в 22:01

50000 руб./за проект

Минуточку внимания

В первой главе мы познакомились с таким типом данных, как строка (str). Мы умеем складывать строки, умножать их на число и даже сравнивать между собой.

Если рассмотреть строку детальнее, то она состоит из символов, каждый из которых стоит на своём месте. Другими словами, строка — упорядоченная последовательность (коллекция) символов.

Слово «коллекция» в Python применяется не только к строкам. Коллекциями в Python также называют типы данных, в которых можно хранить сразу несколько значений.

В упорядоченных коллекциях, к которым относится строка, каждое значение автоматически имеет свой номер — индекс. Индексация в коллекциях Python начинается со значения 0. При этом пробел, запятая, управляющие символы n, t и прочие тоже получают свой индекс в строке. Для доступа к определённому символу строки по индексу нужно указать его в квадратных скобках сразу после имени переменной.

Давайте создадим программу, которая выводит первый символ строки, введённой пользователем:

text = input()
print(text[0])

Если пользователь введёт пустую строку, то наша программа выдаст ошибку:

IndexError: string index out of range

В пустой строке нет символов, и программа вышла за пределы строки. Таким образом, нельзя получить значение по индексу, который за пределами строки. Перед обращением к символу строки по индексу можно проверять, не выходит ли он за пределы строки, используя известную нам функцию len следующим образом:

text = input("Введите строку: ")
i = int(input("Введите индекс символа: "))
if i < len(text):
    print(text[i])
else:
    print("Индекс выходит за пределы строки")

Давайте подумаем, как можно взять последний символ строки? Для этого нам потребуется воспользоваться функцией len:

text = input()
print(text[len(text) - 1])

Однако в Python можно упростить эту запись, убрав из неё функцию len. И тогда в качестве индекса просто будет использоваться отрицательное число:

text = input()
print(text[-1])

Таким образом, последний символ имеет индекс -1, предпоследний -2 и т. д.

Так как строка — упорядоченная коллекция, то можно пройти по этой коллекции в цикле, указав в качестве индекса итерируемую переменную цикла. Например, вывести на строке каждый символ введённой пользователем строки:

text = input()
for i in range(len(text)):
    print(text[i])

Существует и другой способ пройти по символам строки в цикле. Если не требуется на каждой итерации цикла знать индекс текущего символа, то цикл можно оформить следующим образом:

text = input()
for letter in text:
    print(letter)

При такой записи цикла программа проходит не по индексам строки, а непосредственно по её символам. Так, переменная letter на каждой итерации цикла принимает значение очередного символа строки text.

Если требуется совместить проход непосредственно по символам строки с определением индекса итерации, то можно воспользоваться функцией enumerate. Она возвращает пары значений — номер элемента коллекции и сам этот элемент. Эта функция удобна, когда нужно пройти именно по элементам коллекции, но при этом ещё и знать индекс каждого элемента.

text = input()
for i, letter in enumerate(text):
    print(f"{i}. {letter}")

Для строк в Python существует ещё одна полезная операция — срез (slice).

Срез позволяет взять часть строки, указав начальный и конечный индексы (конечный индекс не включается в диапазон). Также можно указать шаг, с которым срез будет взят (по умолчанию шаг 1). Например, в одной из прошлых глав мы аналогичным образом использовали функцию range.

Кроме того, в срезах можно использовать отрицательную индексацию. А если срез выходит за пределы строки, то программа не упадёт с ошибкой, а просто вернёт существующую часть строки.

Следующий пример показывает возможные варианты использования срезов:

text = "Привет, мир!"
print(text[8:11])
print(text[:6])
print(text[8:])
print(text[:])
print(text[::2])

Обратите внимание: строка является неизменяемой коллекцией. Это означает, что изменить отдельный символ строки нельзя.

Например, попытаемся в следующей программе изменить значение одного из символов строки:

word = "мир"
word[0] = "п"

Программа выдаст ошибку:

TypeError: 'str' object does not support item assignment

Мы уже знаем, что взаимодействовать с переменными в Python можно с помощью операций и функций. Рассмотрим ещё один способ взаимодействия — методы.

Методы похожи на функции, но вызываются не сами по себе, а для конкретной переменной. Для каждого типа данных есть свой набор методов. Чтобы вызвать метод, его нужно указать через точку после имени переменной. В круглых скобках после имени метода дополнительно можно обозначить аргументы (параметры) вызываемого метода, как это делаем с функциями.

Например, у строк есть метод islower(), который проверяет, что в строке не встречаются большие буквы, и возвращает в таком случае значение True, иначе — False:

print("а".islower())
print("A".islower())
True
False

В следующей таблице перечислены часто используемые методы строк и примеры их работы. Важный момент: методы строк не меняют исходную строку, а возвращают новое значение, которое можно сохранить в переменной.

str.capitalize()

Метод str.capitalize()
Описание Возвращает копию строки, у которой первая буква заглавная, а остальные приведены к строчным
Пример s = «hello, World!»
s.capitalize()
Результат Hello, world!

str.count(sub)

Метод str.count(sub)
Описание Возвращает количество неперекрывающихся вхождений подстроки sub. К примеру, если искать в строке «ААААА» неперекрывающиеся значения «АА», то первое вхождение будет «AAAAA». Второе — «AAAAA». Больше неперекрывающихся вхождений нет. Так, поиск последующих вхождений подстроки происходит с индекса, который следует за последним найденным вхождением
Пример s = «Hello, world!»
s.count(«l»)
Результат 3

str.endswith(suffix)

Метод str.endswith(suffix)
Описание Возвращает True, если строка оканчивается на подстроку suffix. Иначе возвращает False. suffix может быть кортежем проверяемых окончаний строки
Пример s = «Hello, world!»
s.endswith(«world!»)
Результат True

str.find(sub)

Метод str.find(sub)
Описание Возвращает индекс первого вхождения подстроки sub. Если подстрока не найдена, то возвращает -1
Пример s = «Hello, world!»
s.find(«o»)
Результат 4

str.index(sub)

Метод str.index(sub)
Описание Возвращает индекс первого вхождения подстроки sub. Вызывает исключение ValueError, если подстрока не найдена. Тема ошибок (исключений) будет разбираться на одной из следующих глав
Пример s = «Hello, world!»
s.index(«o»)
Результат 4

str.isalnum()

Метод str.isalnum()
Описание Возвращает True, если все символы строки являются буквами и цифрами и в строке есть хотя бы один символ. Иначе возвращает False
Пример s = «abc123»
s.isalnum()
Результат True

str.isalpha()

Метод str.isalpha()
Описание Возвращает True, если все символы строки являются буквами и в строке есть хотя бы один символ. Иначе возвращает False
Пример s = «Letters»
s.isalpha()
Результат True

str.isdigit()

Метод str.isdigit()
Описание Возвращает True, если все символы строки являются цифрами и в строке есть хотя бы один символ. Иначе возвращает False
Пример s = «123»
s.isdigit()
Результат True

str.islower()

Метод str.islower()
Описание Возвращает True, если все буквы в строке маленькие и в строке есть хотя бы одна буква. Иначе возвращает False
Пример s = «word123»
s.islower()
Результат True

str.isupper()

Метод str.isupper()
Описание Возвращает True, если все буквы в строке большие и в строке есть хотя бы одна буква. Иначе возвращает False
Пример s = «WORD123»
s.isupper()
Результат True

str.join(str_col)

Метод str.join(str_col)
Описание Возвращает строку, полученную конкатенацией (сложением) строк — элементов коллекции str_col (обозначение коллекции с элементами типа данных «строка»). Разделителем является строка, для которой вызван метод
Пример a = [«1», «2», «3»]
«; «.join(a)
Результат «1; 2; 3»

str.ljust(width, fillchar)

Метод str.ljust(width, fillchar)
Описание Возвращает строку длиной width с выравниванием по левому краю. Строка дополняется справа символами fillchar до требуемой длины. По умолчанию значение fillchar — пробел
Пример s = «text»
s.ljust(10, «=»)
Результат «text======»

str.rstrip(chars)

Метод str.rstrip(chars)
Описание Возвращает строку, у которой в конце удалены символы, встречающиеся в строке chars. Если значение chars не задано, то пробельные символы удаляются
Пример s = «stringBCCA»
s.rstrip(«ABC»)
Результат «string»

str.split(sep)

Метод str.split(sep)
Описание Возвращает список строк по разделителю sep. По умолчанию sep — любое количество пробельных символов
Пример s = «one, two, three»
s.split(«, «)
Результат [«one», «two», «three»]

str.startswith(prefix)

Метод str.startswith(prefix)
Описание Возвращает True, если строка начинается на подстроку prefix, иначе возвращает False. prefix может быть кортежем проверяемых префиксов строки. Под кортежами подразумевается неизменяемая последовательность элементов
Пример s = «Hello, world!»
s.startswith(«Hello»)
Результат True

str.strip(chars)

Метод str.strip(chars)
Описание Возвращает строку, у которой в начале и в конце удалены символы, встречающиеся в строке chars. Если значение chars не задано, то пробельные символы удаляются
Пример s = «abc Hello, world! cba»
s.strip(» abc»)
Результат «Hello, world!»

str.title()

Метод str.title()
Описание Возвращает строку, в которой каждое отдельное слово начинается с буквы в верхнем регистре, а остальные буквы идут в нижнем
Пример s = «hello, world!»
s.title()
Результат «Hello, World!»

str.upper()

Метод str.upper()
Описание Возвращает копию строки, у которой все буквы приведены к верхнему регистру
Пример s = «Hello, world!»
s.upper()
Результат «HELLO, WORLD!»

str.zfill(width)

Метод str.zfill(width)
Описание Возвращает строку, дополненную слева символами «0» до длины width
Пример s = «123»
s.zfill(5)
Результат «00123»

Рассмотрим ещё одну коллекцию в Python — список (list). Этот тип данных является упорядоченной коллекцией, которая может в качестве элементов иметь значения любого типа данных.

Один из способов создания списков — перечислить его элементы в квадратных скобках и присвоить это значение переменной, которая и станет в итоге списком в программе:

numbers = [10, 20, 30]

В примере мы создали список, состоящий из трёх элементов — целых чисел. Список может хранить значения любого типа, поэтому можно создать список со следующими элементами:

mixed_list = [10, 20.55, "text"]

Индексация в списках работает так же, как и в строках, — начальный индекс 0. Можно использовать отрицательные индексы, а также доступны срезы:

numbers = [10, 20, 30, 40, 50]
print(numbers[0])
print(numbers[-1])
print(numbers[1:3])
print(numbers[::-1])

Результат работы программы:

10
50
[20, 30]
[50, 40, 30, 20, 10]

В отличие от строки, список относится к изменяемой коллекции. У списка можно изменить отдельный элемент, добавить новые или удалить существующие. Для изменения существующего элемента нужно указать его в левой части операции присваивания, а в правой указать новое значение этого элемента:

numbers = [10, 20, 50]
numbers[2] = 30
print(numbers)

Вывод программы:

[10, 20, 30]

Если требуется добавить элемент в конец списка, то можно использовать метод append().

Например, напишем программу, в которой список последовательно заполняется 10 целочисленными значениями с клавиатуры:

numbers = []
for i in range(10):
    numbers.append(int(input()))
print(numbers)

Вывод программы:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Для удаления элемента из списка применяется операция del. Нужно указать индекс элемента, который требуется удалить:

numbers = [10, 20, 50]
del numbers[-1]
print(numbers)

Вывод программы:

[10, 20]

С помощью del можно удалить несколько элементов списка. Для этого вместо одного элемента указываем срез:

numbers = [1, 2, 3, 4, 5]
del numbers[::2]
print(numbers)

Вывод программы:

[2, 4]

Полезные методы и функции списков и примеры их работы приведены в следующей таблице.

Операция Описание Пример Результат
x in s Возвращает True, если в списке s есть элемент x. Иначе False 1 in [1, 2, 3] True
x not in s Возвращает False, если в списке s есть элемент x. Иначе True 4 not in [1, 2, 3] True
s + t Возвращает список, полученный конкатенацией списков s и t [1, 2] + [3, 4, 5] [1, 2, 3, 4, 5]
s * n (n * s) Возвращает список, полученный дублированием n раз списка s [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
len(s) Возвращает длину списка s len([1, 2, 3]) 3
min(s) Возвращает минимальный элемент списка min([1, 2, 3]) 1
max(s) Возвращает максимальный элемент списка max([1, 2, 3]) 3
s.index(x) Возвращает индекс первого найденного элемента x. Вызывается исключение ValueError, если элемент не найден [1, 2, 3, 2, 1].index(2) 1
s.count(x) Возвращает количество элементов x [1, 1, 1, 2, 3, 1].count(1) 4
s.append(x) Добавляет элемент x в конец списка s = [1, 2]
s.append(3)
print(s)
[1, 2, 3]
s.clear() Удаляет все элементы списка s = [1, 2, 3]
s.clear()
print(s)
[]
s.copy() Возвращает копию списка [1, 2, 3].copy() [1, 2, 3]
s.extend(t) или s += t Расширяет список s элементами списка t s = [1, 2, 3]
s.extend([4, 5])
print(s)
[1, 2, 3, 4, 5]
s.insert(i, x) Вставляет элемент x в список по индексу i s = [1, 3, 4]
s.insert(1, 2)
print(s)
[1, 2, 3, 4]
s.pop(i) Возвращает и удаляет элемент с индексом i. Если i не указан, то возвращается и удаляется последний элемент s = [1, 2, 3]
x = s.pop()
print(x)
print(s)
3
[1, 2]
s.remove(x) Удаляет первый элемент со значением x s = [1, 2, 3, 2, 1]
s.remove(2)
print(s)
[1, 3, 2, 1]
s.reverse() Меняет порядок элементов списка на противоположный (переворачивает список) s = [1, 2, 3]
s.reverse()
print(s)
[3, 2, 1]
s.sort() Сортирует список по возрастанию, меняя исходный список. Для сортировки по убыванию используется дополнительный аргумент reverse=True s = [2, 3, 1]
s.sort()
print(s)
[1, 2, 3]
sorted(s) Возвращает отсортированный по возрастанию список, не меняя исходный. Для сортировки по убыванию используется дополнительный аргумент reverse=True s = [2, 3, 1]
new_s = sorted(s, reverse=True)
print(new_s)
[3, 2, 1]

Ещё одной коллекцией в Python является кортеж (tuple). Кортеж является неизменяемой упорядоченной коллекцией. В кортеже нельзя заменить значение элемента, добавить или удалить элемент. Простыми словами, кортеж — неизменяемый список. Свойство неизменяемости используется для защиты от случайных или намеренных изменений.

Задать кортеж можно следующим образом:

numbers = (1, 2, 3, 4, 5)

Если нужно создать кортеж из одного элемента, то запись будет такой:

one_number = (1, )

Запятая в примере показывает, что в скобках не совершается операция, а идёт перечисление элементов кортежа.

Для кортежей доступны те операции и методы списков, которые не изменяют исходный кортеж.

В качестве примера использования кортежей приведём программу для обмена значений двух переменных:

a = 1
b = 2
(a, b) = (b, a)
# можно опустить круглые скобки и записать так a, b = b, a
print(f"a = {a}, b = {b}")

Вывод программы:

a = 2, b = 1

Между коллекциями можно производить преобразования. Покажем их на примере преобразования строки в список и кортеж (элементы строки, символы становятся элементами списка и кортежа соответственно):

text = "Привет, мир!"
list_symbols = list(text)
tuple_symbols = tuple(text)
text_from_list = str(list_symbols)
print(list_symbols)
print(tuple_symbols)
print(text_from_list)

Вывод программы:

['П', 'р', 'и', 'в', 'е', 'т', ',', ' ', 'м', 'и', 'р', '!']
('П', 'р', 'и', 'в', 'е', 'т', ',', ' ', 'м', 'и', 'р', '!')
['П', 'р', 'и', 'в', 'е', 'т', ',', ' ', 'м', 'и', 'р', '!']

Обратите внимание: преобразование коллекций к типу данных str не объединяет элементы этой коллекции в одну строку, а возвращает представление коллекции в виде строки.

Понравилась статья? Поделить с друзьями:
  • Index was outside the bounds of the array ошибка
  • Index php 500 internal server error
  • Index is out of date как исправить
  • Index exceeds matrix dimensions матлаб как исправить
  • Index error tuple index out of range