Lowercase python ошибка

I think I’m having troubles importing pylab. A similar error occurs when I import numpy.
Here is my code

from math import radians, sin, cos
from pylab import plot, xlabel, ylabel, title, show

v0=input("Enter v0 (m/s)...")
alpha0=input("enter alpha0 (degrees)...")
g=input("Enter g (m/s^2)..")

radalpha0=radians(alpha0)
t_inc=0.01
t=0
i=0
x=[]
y=[]

x.append(v0*cos(radalpha0)*t)
y.append(v0*sin(radalpha0)*t-0.5*g*t*t)

while y[i]>=0:
    i=i+1
    t=t+t_inc
    x.append(v0*cos(radalpha0)*t)
    y.append(v0*sin(radalpha0)*t-0.5*g*t*t)

xlabel('x')
ylabel('x')
plot(x,y)
title('Motion in two dimensions')
show()

I get this output

Traceback (most recent call last):
  File "2d_motion.py", line 2, in <module>
    from pylab import plot, xlabel, ylabel, title, show
  File "/usr/lib64/python2.7/site-packages/pylab.py", line 1, in <module>
    from matplotlib.pylab import *
  File "/usr/lib64/python2.7/site-packages/matplotlib/__init__.py", line 151, in <module>
    from matplotlib.rcsetup import (defaultParams,
  File "/usr/lib64/python2.7/site-packages/matplotlib/rcsetup.py", line 19, in <module>
    from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
  File "/usr/lib64/python2.7/site-packages/matplotlib/fontconfig_pattern.py", line 28, in <module>
    from pyparsing import Literal, ZeroOrMore, 
  File "/usr/lib/python2.7/site-packages/pyparsing.py", line 109, in <module>
    alphas = string.lowercase + string.uppercase
AttributeError: 'module' object has no attribute 'lowercase'

Is there any problem with the syntax?

I’m using python2.7 on fedora18.

(I’m quite an amateur here, so go easy!). I can’t seem to get past this error:

Runtime error 
Traceback (most recent call last):
  File "<string>", line 31, in <module>
AttributeError: 'tuple' object has no attribute 'lowercase'

Here is a simplified version of my code:

import pyodbc

#connect to SQL Server database
db=pyodbc.connect("DRIVER={SQL Server Native Client 11.0};SERVER=NotAChance;DATABASE=theCan;UID=HAHA;PWD=NotGonnaTell;")

#set the database cursor
c=db.cursor()

#SQL for getting PIDs that have feature classes locked
c.execute("""SELECT DISTINCT sde.SDE_table_locks.*,
sde.SDE_process_information.start_time,
sde.SDE_process_information.owner,
sde.SDE_process_information.nodename,
sde.SDE_process_information.direct_connect,
sde.SDE_table_registry.table_name
FROM sde.SDE_table_locks
INNER JOIN sde.SDE_table_registry ON sde.SDE_table_locks.registration_id = sde.SDE_table_registry.registration_id
WHERE (sde.SDE_table_registry.table_name) Like '%%'""")

#Create a list to dump PIDs in to, so we can weed down to unique ones
mylist = []

#Loop through the PIDs 
for (a, b, c, d, e, f, g, h, i) in c.fetchall():

    #add the PID that needs to be killed to a list
    mylist.append(b)
    #print (mylist)

#weed the list of PIDs down to just the unique PIDs
pids_to_kill = dict(map(lambda i: (i,1),mylist)).keys()

arcpy.AddMessage(pids_to_kill)

#reset the cursor
c=db.cursor()

#loop through the unique PIDs and delete each lock record
for i in pids_to_kill:
    c.execute("DELETE FROM sde.SDE_table_locks WHERE sde.SDE_table_locks.registration_id = " + str(i))
    c=db.cursor()

#commit the changes
db.commit()

#disconnect
db.close()

I’m having trouble understanding the issue it’s having with my tuple. I’m not doing anything with .lower() anywhere in the code.

I’m using Python 2.7 and running this in ArcGIS 10.5 (python window, as well as in a script tool). This could potentially go in the GIS Stack Exchange, but I’m not sure it’s particularly GIS-related.

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’
    • Python lower() Syntax
  • Example
    • Solution
  • Summary

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:

string.lower()

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

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:

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

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

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!

Метод lower() — один из многих встроенных в Python методов для работы со строками. Он крайне удобен и прост в использовании.

В этой статье мы на примерах рассмотрим, как с помощью данного метода переводить строки в нижний регистр. Однако давайте начнем с определения строки в Python.

Что такое строка?

Строка — это тип данных в Python. Строка записывается как последовательность символов, заключенная в одинарные или двойные кавычки.

К примеру, строка может выглядеть так:

>>> example_string = 'I am a String!'
>>> example_string
'I am a String!'

Подробнее про строки можно почитать в статье «Строки в Python 3. Введение в работу со строками».

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

Что такое метод?

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

Иногда вы можете задаться вопросом, существует ли какой-то метод. В Python можно посмотреть весь список строковых методов, используя функцию dir() со строкой в ​​качестве аргумента:

>>> dir(example_string)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Точно так же, при помощи функции dir(), можно узнать методы и других типов данных.

В этой статье мы рассмотрим лишь один строковый метод — lower(). Познакомиться с другими методами строк можно, заглянув в статью «Методы строк в Python».

[python_ad_block]

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

Например, можно использовать метод lower() вот так:

>>> example_string.lower()
'i am a string!'

>>> 'PYTHONIST'.lower()
'pythonist'

Что следует учитывать при использовании метода lower()

Метод lower() делает довольно простую вещь. Он создает новую строку, в которой все прописные буквы меняются на строчные. Но есть несколько моментов, о которых следует помнить при его использовании.

Строки неизменяемы

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

В приведенных выше примерах метод lower() применяется к строке example_string, но он ее не изменяет. Проверьте значение example_string и вы увидите, что оно осталось прежним:

>>> example_string
'I am a String!'

>>> example_string.lower()
'i am a string!'

>>> example_string
'I am a String!'

Метод lower() возвращает новую строку

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

>>> new_string = example_string.lower()

>>> new_string
'i am a string!'

Строки чувствительны к регистру

Строки чувствительны к регистру, поэтому строка нижнего регистра отличается от строки верхнего регистра. Это явно видно из примера ниже:

>>> 'pythonist' == 'PYTHONIST'
False

Именно эта особенность строк делает метод lower() полезным при написании скриптов или программ для работы со строками.

Пример работы метода lower(): проверяем пользовательский ввод

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

Данная программа будет выглядеть следующим образом:

answer = input("What color is the sun? ")
if answer == "yellow":
    print("Correct!")
else:
    print("That is not the correct color!")

Скрипт задает пользователю вопрос "What color is the sun?" («Какого цвета солнце?») и ждет от него ответа. Затем программа проверяет, совпадает ли ответ с "yellow" (желтый), и если да, то печатает "Correct!" («Правильно!»). Если пользователь введет другой ответ, программа напечатает "That is not the correct color!" («Это неправильный цвет!»).

Однако с этим скриптом есть явная проблема. Запустив данную программу, вы получите вопрос в терминале:

$ python sun_color.py
What color is the sun? 

Но если вы ответите "Yellow" («Желтый»), то программа ответит, что цвет неправильный:

$ python sun_color.py
What color is the sun? Yellow
That is not the correct color!

Почему так происходит?

Помните, что строки чувствительны к регистру. Программа проверяет, совпадает ли пользовательский ответ со строкой yellow. Однако  — Yellow с заглавной буквой Y — это совершенно другая строка.

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

answer = input("What color is the sun? ")
if answer.lower() == "yellow":
  print("Correct!")
else:
  print("That is not the correct color!")

И вот теперь, запустив программу заново, вы получите ожидаемое поведение:

>>> python sun_color.py
What color is the sun? Yellow
Correct!

Что изменилось? Указав answer.lower(), вы переводите пользовательский input в нижний регистр, а уж затем сравниваете результат с правильной строкой ответа yellow. Таким образом, не имеет значения, напишет пользователь YELLOW, yELLOW, yellow или как-то ещё — все это преобразуется в нижний регистр.

Заключение

Итак, мы повторили, что такое строки, узнали, как посмотреть все доступные строковые методы, и рассмотрели один из них — метод lower().

Надеемся, данная статья была для вас полезна! Успехов в написании кода!

Перевод статьи «Python Lowercase – How to Use the String lower() Function».

Python 3: Changing Strings to Lower Case: Error ‘function’ object has no attribute ‘lower’

I am trying to make a function that can take any string with a mix of upper and lower case letters and turn it into all lower case letters. I am doing this on LeetCode. I put in the following code:

class Solution:
    def toLowerCase(self, str):
        """
        :type str: str
        :rtype: str
        """
        solution_test = Solution()
        return solution_test.toLowerCase.lower();

I got the following error:

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

How do I fix this?

Archived post. New comments cannot be posted and votes cannot be cast.

Понравилась статья? Поделить с друзьями:
  • Lower blue lever ошибка
  • Low range ошибка туарег
  • Low idle ошибка
  • Low fuel jcb ошибка
  • Low brake performance ошибка даф 105