You can handle the positive case using the following:

In [150]:
import re
df['fundleverage'] = '+' + df['name'].str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X') + '00'
df

Out[150]:
                 name fundleverage
0  BULL AXP UN X3 VON         +300
1    BULL ESTOX X12 S        +1200

You can use np.where to handle both cases in a one liner:

In [151]:
df['fundleverage'] = np.where(df['name'].str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X').str.isdigit(),  '+' + df['name'].str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X') + '00', '+100')
df

Out[151]:
                 name fundleverage
0  BULL AXP UN X3 VON         +300
1    BULL ESTOX X12 S        +1200

So the above uses the vectorised str methods strip, extract and isdigit to achieve what you want.

Update

After you changed your requirements (which you should not do for future reference) you can mask the df for the bull and bear cases:

In [189]:
import re
df = pd.DataFrame(["BULL AXP UN X3 VON", "BEAR ESTOX 12x S"], columns=["name"])
bull_mask_name = df.loc[df['name'].str.contains('bull', case=False), 'name']
bear_mask_name = df.loc[df['name'].str.contains('bear', case=False), 'name']
df.loc[df['name'].str.contains('bull', case=False), 'fundleverage'] = np.where(bull_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X').str.isdigit(),  '+' + bull_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X') + '00', '+100')
df.loc[df['name'].str.contains('bear', case=False), 'fundleverage'] = np.where(bear_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('x').str.isdigit(),  '-' + bear_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('x') + '00', '-100')
df

Out[189]:
                 name fundleverage
0  BULL AXP UN X3 VON         +300
1    BEAR ESTOX 12x S        -1200
Answer from EdChum on Stack Overflow
Top answer
1 of 1
2

You can handle the positive case using the following:

In [150]:
import re
df['fundleverage'] = '+' + df['name'].str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X') + '00'
df

Out[150]:
                 name fundleverage
0  BULL AXP UN X3 VON         +300
1    BULL ESTOX X12 S        +1200

You can use np.where to handle both cases in a one liner:

In [151]:
df['fundleverage'] = np.where(df['name'].str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X').str.isdigit(),  '+' + df['name'].str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X') + '00', '+100')
df

Out[151]:
                 name fundleverage
0  BULL AXP UN X3 VON         +300
1    BULL ESTOX X12 S        +1200

So the above uses the vectorised str methods strip, extract and isdigit to achieve what you want.

Update

After you changed your requirements (which you should not do for future reference) you can mask the df for the bull and bear cases:

In [189]:
import re
df = pd.DataFrame(["BULL AXP UN X3 VON", "BEAR ESTOX 12x S"], columns=["name"])
bull_mask_name = df.loc[df['name'].str.contains('bull', case=False), 'name']
bear_mask_name = df.loc[df['name'].str.contains('bear', case=False), 'name']
df.loc[df['name'].str.contains('bull', case=False), 'fundleverage'] = np.where(bull_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X').str.isdigit(),  '+' + bull_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('X') + '00', '+100')
df.loc[df['name'].str.contains('bear', case=False), 'fundleverage'] = np.where(bear_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('x').str.isdigit(),  '-' + bear_mask_name.str.extract(r"(X\d+|\d+X)\s", flags=re.IGNORECASE).str.strip('x') + '00', '-100')
df

Out[189]:
                 name fundleverage
0  BULL AXP UN X3 VON         +300
1    BEAR ESTOX 12x S        -1200
Discussions

python - Attribute Error: 'str' object has no attribute 'str' - Stack Overflow
I have a dataframe column which contains URLs. I want to extract a specific string out of this URL by using a regex pattern for each row. Here is an example of the URL string: 'www.abcdef.com/spor... More on stackoverflow.com
🌐 stackoverflow.com
python - AttributeError: 'str' object has no attribute 'str' - Stack Overflow
My pandas DataFrame looks like following. I am trying to remove '$' and ',' from my income column and then apply on my original dataframe. so I created below function. However, it is giving me error More on stackoverflow.com
🌐 stackoverflow.com
python - AttributeError: 'str' object has no attribute 'xpath' - Stack Overflow
Using Python 3,Scrapy 1.7.3 to Following using following link Scrapy - Extract items from table but it is giving me error of AttributeError: 'str' object has no attribute 'xpath' More on stackoverflow.com
🌐 stackoverflow.com
python - Apply function 'str' object has no attribute 'str' - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
January 20, 2022
🌐
Esri Community
community.esri.com › t5 › arcgis-api-for-python-questions › str-object-has-no-attribute › td-p › 1053478
Solved: 'str' object has no attribute - Esri Community
September 14, 2021 - Solved: Searching through the other messages hasn't helped me with this. I like to figure things out on my own, but I'm stumped. I copied the deep_copy_content part
Find elsewhere
Top answer
1 of 1
2

Since

self.board = [['.']*8 for _ in range(8)]

for some values of i and j, self.board[i][j] is a string. Therefore,

self.board[i][j].sl=='R'

is raising AttributeError: 'str' object has no attribute 'sl' because strings have no sl attribute.


Perhaps the easiest way to fix your code with minimal changes would be to add an Empty class similar to other chess piece classes to represent unoccupied squares on the chess board. Make sure instances of the Empty class have an sl attribute.

Note however that it is not clear (to me) that you really need separate classes for each kind of chess piece. They are all basically the same kind of object, they merely differ in terms of how they move. So you may be better off with one chess piece class and give each instance a kind attribute which could equal 'rook', 'knight', etc.

Also note that in your code there is redundant information: The self.board records the location of the pieces, and the chess piece also records the location:

    self.board[7][0] = Rook(x=7,y=0,sl='R',team='white')

Recording the information in two places poses a problem:

  • The information may become corrupted -- if the logic in your code is not correct, the board may record the location of a piece in a different place than where the piece itself thinks it is on the board. Thus you have a coordination problem.

  • Having the information in two places makes your code more complicated because you have to update the location in both the board and the chess piece to maintain consistency every time a piece is moved.

🌐
Reddit
reddit.com › r/learnpython › attributeerror: 'str' object has no attribute 'namelist' in python
r/learnpython on Reddit: AttributeError: 'str' object has no attribute 'namelist' in Python
September 22, 2020 -

At this line:
zipfile.ZipFile.extractall(zip, None, pwd=str.encode(pwd))
i allways get the error (in the title).
My zip path (as string zip) is like this:
zipFile = r'/home/itsthooor/This That/Empty.zip'

Where's the problem?
I saw a stack overflow post about it, but it didn't me help at all.

🌐
Stack Overflow
stackoverflow.com › questions › 63203054 › why-do-i-get-this-error-attributeerror-str-object-has-no-attribute-get-wher
python - Why do I get this error AttributeError: 'str' object has no attribute 'get' where the get function is on a dictionary? - Stack Overflow
This question does not meet Stack Overflow guidelines. It is not currently accepting answers. This question does not appear to be about programming within the scope defined in the help center. Closed 5 years ago. ... This fruits dictionary is passed and returned in many functions. I am not sure why but in this line of code I get an AttributeError...
Top answer
1 of 2
1

Your code has multiple problems - not just the one that has been answered by @Tanishq

You entire approach is not ideal. It's much better to limit your Student class to storing data and handling its representation. Acquisition of the data should be dealt with separately.

Something like this:

Copyfrom typing import Any

class Student:
    def __init__(self, name: str):
        self._name: str = name
        self._data: dict[str, float] = {}
        
    def __add__(self, __value: Any) -> 'Student':
        subject, score = __value
        self._data[subject] = score
        return self

    def __str__(self):
        r = [self._name]
        for subject, score in self._data.items():
            r.append(f'{subject} -> {score}')
        return '\n'.join(r)

name = input('Student name: ')
student = Student(name)
n = int(input('Number of subjects: '))
for _ in range(n):
    subject = input('Subject name: ')
    score = float(input('Score: '))
    student += (subject, score)
print(student)

Console example:

CopyStudent name: John
Number of subjects: 2
Subject name: English
Score: 65
Subject name: Geography
Score: 58
John
English -> 65.0
Geography -> 58.0

Note:

Numeric input validation omitted for brevity

2 of 2
0

Here is one way of doing what you want

Copyclass student(object):
    def __init__(self, standard: int, name: str, age: int, address: str):
       self.standard = standard
       self.name = name
       self.age = age
       self.address = address
       
       self.calc()

    def calc(self):
        self.subject = []
        self.score = []

        N = (int)(input('Please enter number of Subjects: '))

        for i in range(N):
            item = input('Enter Subject name: ').upper()
            self.subject.append(item)
        
        for i in range(len(self.subject)):
            item = input(f'Please Enter the score for {self.subject[i]}: ')
            self.score.append(item)


student1 = student(standard=10, name="foo", age=13, address="bar")

Your error:

  • You are directly calling the calc function of the class, student, without instantiating it. (You can checkout staticmethods in Python if you still want to do this.)
  • The self is then treated as a variable name, and since you pass '' as the value of self, it is inferred to be a string.
  • This is why you get the error, that the str has no attribute name - because the self is a string and not the instance.

Some notes:

  • You need to instantiate the class, student, and pass in the required arguments (as shown in the last line of my solution).
  • You can merge the print before the input into one, as shown.
  • You can merge the calc function with __init__, as mentioned in the comments.
  • You are returning within the for loop, after you do self.subject.append(...). This will not let to have more than 1 subject, and your scores will always be empty - since the function calc will never reach the score handling section.
  • You might want to look at exception handling to handle the input of number of subjects, here.
Top answer
1 of 1
1
  • Correcting the code as shown below after following the links given in the comments by @SolomonUcko, the requirement was achieved without any error and status as succeeded.

from azure.identity import DefaultAzureCredential, ClientSecretCredential
from azure.synapse.artifacts import ArtifactsClient
from azure.synapse.artifacts.models import SqlScript,SqlScriptContent,SqlScriptResource,SqlConnection
import json


workspace_name = 'synapse2403'
subscription_id = '<subscription_id>'
resource_group = '<resource_grp'
workspace_endpoint = f"https://<workspace_name>.dev.azuresynapse.net"

#my credentials
tenant_id='<tenant_id>'
client_id='<client_id>'
client_secret='<client_secret>'
credential = ClientSecretCredential(tenant_id,client_id,client_secret)

client = ArtifactsClient(
credential = credential,
subscription_id = subscription_id,
endpoint = workspace_endpoint
)

#sql script as string
sql_script_content='create table demo(id int, gname varchar(40))'


sql_conn = SqlConnection(name='pool1',type='SqlPool')   #SqlConnection object for SqlScriptContent
sql_cnt = SqlScriptContent(query = sql_script_content, current_connection=sql_conn)    #SqlScriptContent object for SqlScript
sql_scrpt = SqlScript(type = 'SqlQuery', content = sql_cnt)    #SqlScript object for SqlScriptResource 
sql_resource = SqlScriptResource(name = 'myresource', properties = sql_scrpt)    #SqlScriptResource for begin_create_or_update_sql_script
sql_scripts_operations = client.sql_script

create_or_update_script_response = sql_scripts_operations.begin_create_or_update_sql_script(
sql_script_name = 'sql_query.sql',
sql_script = sql_resource
)

  • The following is the output image for reference.

🌐
Python Forum
python-forum.io › thread-22378.html
AttributeError: 'str' object has no attribute 'xpath'
Dear Members, I am very new to python. I am using the following code to extract the details of each product. I am collecting product names from the original page and using each product link, I am collecting price, SKU, and frame information from th...
🌐
Stack Overflow
stackoverflow.com › questions › 65822233 › attributeerror-str-object-has-no-attribute-description
python - AttributeError: 'str' object has no attribute 'description' - Stack Overflow
Im new in Python3. I wrote a little text-adventure but i don't know how to use the input string to access the object properties. class Object: def __init__(self, name, description): sel...
🌐
Stack Overflow
stackoverflow.com › questions › 72848918 › attributeerror-str-object-has-no-attribute-str-how-to-solve-this
python - AttributeError: 'str' object has no attribute 'str' how to solve this - Stack Overflow
When I apply f"" string on my text data it procduces the following error. AttributeError: 'str' object has no attribute 'str'. The simple code is below, I am providing just one line so th...
🌐
freeCodeCamp
forum.freecodecamp.org › python
AttributeError: 'str' object has no attribute 'get' - Python - The freeCodeCamp Forum
December 2, 2021 - The formatting of your post is hella weird - how about you just include a link to your replit · For the catplot, you need to add a line fig=fig.fig before saving - as the test is not designed for standard object sns is returning · Am sorry for my formatting errors Jagaya, am new to this .
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1327627 › result-failure-exception-attributeerror-str-object
Result: Failure Exception: AttributeError: 'str' object has no attribute 'get' at project_id = req_body.get("project_id", None) this - Microsoft Q&A
July 10, 2023 - def main(req: func.HttpRequest) -> func.HttpResponse: try: req_body = req.get_json() print(req_body) project_id = req_body.get("project_id", None) print(project_id) except ValueError: filterdata…