Python lower не работает

Метод string lower() и upper() в Python

Метод string lower() преобразует все символы верхнего регистра в строке в символы нижнего регистра и возвращает их.

Параметры

Метод в Python не принимает никаких параметров.

Возвращаемое значение

Команда возвращает строку в нижнем регистре из данной строки. Он преобразует все символы верхнего регистра в нижний регистр.

Если символы верхнего регистра отсутствуют, возвращается исходная строка.

Пример 1: Преобразование строки в нижний регистр

# example string string = "THIS SHOULD BE LOWERCASE!" print(string.lower()) # string with numbers # all alphabets whould be lowercase string = "Th!s Sh0uLd B3 L0w3rCas3!" print(string.lower())
this should be lowercase! th!s sh0uld b3 l0w3rcas3!

Пример метода lower()

# first string firstString = "PYTHON IS AWESOME!" # second string secondString = "PyThOn Is AwEsOmE!" if(firstString.lower() == secondString.lower()): print("The strings are same.") else: print("The strings are not same.")

Примечание: Если вы хотите преобразовать строку в верхний регистр, используйте upper(). Вы также можете использовать метод swapcase() для переключения между нижним регистром и верхним регистром.

Метод string upper() преобразует все символы нижнего регистра в строке в символы верхнего регистра и возвращает их.

Параметры

Метод upper() в Python не принимает никаких параметров.

Читайте также:  Разработчик языка программирования javascript

Возвращаемое значение

Метод возвращает строку в верхнем регистре из данной строки. Он преобразует все символы нижнего регистра в верхний регистр.

Если строчные символы отсутствуют, возвращается исходная строка.

Пример 1: Преобразование строки в верхний регистр

# example string string = "this should be uppercase!" print(string.upper()) # string with numbers # all alphabets whould be lowercase string = "Th!s Sh0uLd B3 uPp3rCas3!" print(string.upper())
THIS SHOULD BE UPPERCASE! TH!S SH0ULD B3 UPP3RCAS3!

Пример 2: Как в программе используется?

# first string firstString = "python is awesome!" # second string secondString = "PyThOn Is AwEsOmE!" if(firstString.upper() == secondString.upper()): print("The strings are same.") else: print("The strings are not same.")

Примечание: Если вы хотите преобразовать строку в нижний регистр, используйте lower(). Вы также можете использовать swapcase() для переключения между нижним регистром и верхним регистром.

Источник

How to Solve Python AttributeError: ‘list’ object has no attribute ‘lower’

In Python, the list data structure stores elements in sequential order. We can use the String lower() method to get a string with all lowercase characters. However, we cannot apply the lower() function to a list. If you try to use the lower() method on a list, you will raise the error “AttributeError: ‘list’ object has no attribute ‘lower’”.

This tutorial will go into detail on the error definition. We will go through an example that causes the error and how to solve it.

Table of contents

AttributeError: ‘list’ object has no attribute ‘lower’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘list’ object has no attribute ‘lower’” tells us that the list object we are handling does not have the lower attribute. We will raise this error if we try to call the lower() method on a list object. lower() is a string method that returns a string with all lowercase characters.

Python lower() Syntax

The syntax for the String method lower() is as follows:

The lower() method ignores symbols and numbers.

Let’s look at an example of calling the lower() method on a string:

a_str = "pYTHoN" a_str = a_str.lower() print(a_str)

Next, we will see what happens if we try to call lower() on a list:

a_list = ["pYTHoN", "jAvA", "ruBY", "RuST"] a_list = a_list.lower() print(a_list)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) 1 a_list = ["pYTHoN", "jAvA", "ruBY", "RuST"] 2 ----≻ 3 a_list = a_list.lower() 4 5 print(a_list) AttributeError: 'list' object has no attribute 'lower'

The Python interpreter throws the Attribute error because the list object does not have lower() as an attribute.

Example

Let’s look at an example where we read a text file and attempt to convert each line of text to all lowercase characters. First, we will define the text file, which will contain a list of phrases:

CLiMBinG iS Fun RuNNing is EXCitinG SwimmING iS RElaXiNg

We will save the text file under phrases.txt . Next, we will read the file and apply lower() to the data:

data = [line.strip() for line in open("phrases.txt", "r")] print(data) text = [[word for word in data.lower().split()] for word in data] print(text)

The first line creates a list where each item is a line from the phrases.txt file. The second line uses a list comprehension to convert the strings to lowercase. Let’s run the code to see what happens:

['CLiMBinG iS Fun', 'RuNNing is EXCitinG', 'SwimmING iS RElaXiNg'] --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) 1 data = [line.strip() for line in open("phrases.txt", "r")] 2 print(data) ----≻ 3 text = [[word for word in data.lower().split()] for word in data] 4 print(text) AttributeError: 'list' object has no attribute 'lower'

The error occurs because we applied lower() to data which is a list. We can only call lower() on string type objects.

Solution

To solve this error, we can use a nested list comprehension, which is a list comprehension within a list comprehension. Let’s look at the revised code:

data = [line.strip() for line in open("phrases.txt", "r")] print(data) text = [[word.lower() for word in phrase.split()] for phrases in data] print(text)

The nested list comprehension iterates over every phrase, splits it into words using split() , and calls the lower() method on each word. The result is a nested list where each item is a list that contains the lowercase words of each phrase. Let’s run the code to see the final result:

['CLiMBinG iS Fun', 'RuNNing is EXCitinG', 'SwimmING iS RElaXiNg'] [['climbing', 'is', 'fun'], ['running', 'is', 'exciting'], ['swimming', 'is', 'relaxing']]

If you want to flatten the list you can use the sum() function as follows:

flat_text = sum(text, []) print(flat_text)
['climbing', 'is', 'fun', 'running', 'is', 'exciting', 'swimming', 'is', 'relaxing']

There are other ways to flatten a list of lists that you can learn about in the article: How to Flatten a List of Lists in Python.

If we had a text file, where each line is a single word we would not need to use a nested list comprehension to get all-lowercase text. The file to use, words.txt contains:

CLiMBinG RuNNing SwimmING

The code to use is as follows:

text = [word.lower() for word in open('words.txt', 'r')] print(text)

Let’s run the code to see the output:

['climbing', 'running', 'swimming']

Summary

Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘lower’” occurs when you try to use the lower() function to replace a string with another string on a list of strings.

The lower() function is suitable for string type objects. If you want to use the lower() method, ensure that you iterate over the items in the list of strings and call the lower method on each item. You can use list comprehension to access the items in the list.

Generally, check the type of object you are using before you call the lower() method.

For further reading on AttributeErrors involving the list object, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Share this:

Источник

Python .lower не работает без (), мне интересно, почему

Итак, я столкнулся с этим, но не до конца понимаю, почему это так:

 count = 0 Got_one = 0 while(count<1): print('\n') response = input("Did you get one?\n:").lower()#<--This part here if response == 'yes': Got_one += 1 #. ect 

В одном месте сценария я набрал .lower без (). Код работал нормально, но скрипту не удалось +1, когда я ввел "да", вместо этого он напечатал значение 0, скорее всего из-за того, что переменная "Got_one" была установлена ​​в 0 в самом начале. Однако, как только я набрал (), код заработал как положено и +1 к значению после ввода "да".

Итак, почему это так?.Lower сам по себе опускает все после него или просто что-то, чего я еще не понимаю в Python?

5 ответов

.lower() является встроенным методом для объекта String в Python. Причина, по которой вам нужна скобка, заключается в том, чтобы выполнить функцию в строке.

Без скобок вы просто получаете доступ к атрибуту String.lower, который является указателем на функцию. Поэтому без скобок вы устанавливаете response = String.lower , который не пройдет оператор if.

Разница в том, что вызов его без круглых скобок - это просто вызов метода, но не значения этого метода, а вызов с круглыми скобками, вызов значения этого метода

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

Метод класса - это функция, которая принадлежит объекту класса, в данном случае str объект. Атрибут класса - это переменная, которая принадлежит этому объекту.

Источник

Оцените статью