Почему replace не работает python
Перейти к содержимому

Почему replace не работает python

  • автор:

String replace doesn't appear to be working [duplicate]

I initially tried using = operator to assign value but it returned an error, then I tried using string.replace() :

But it is returning the orignal value.

Help out as to how to use the replace API properly to give the correct result Also is there any other API that can be used instead of unichr() .

The encrypted_str is being taken from the user by encrypted_str = raw_input() dec_str2 is the freq string being input by user. The issue hardly concerns the variable I want to know if I am using the replcae() API incorrectly as it is giving me unchanged output for encrypted_str Can we use encrypted_str[j] would return a character from the string to define the sub string for the replace() API. I used encrypted_str.replace(encrypted_str[j], unichr(ord(dec_str2[k]) — 32), 1) max replace 1 instead of 2 (as I need just the one replacement).

The actual operation that I need to be done will be in C as follows: encrypted_str[j] = dec_str2[k] -32 .

Python string replace not working

  • All categories
  • ChatGPT (11)
  • Apache Kafka (84)
  • Apache Spark (596)
  • Azure (145)
  • Big Data Hadoop (1,907)
  • Blockchain (1,673)
  • C# (141)
  • C++ (271)
  • Career Counselling (1,060)
  • Cloud Computing (3,469)
  • Cyber Security & Ethical Hacking (162)
  • Data Analytics (1,266)
  • Database (855)
  • Data Science (76)
  • DevOps & Agile (3,608)
  • Digital Marketing (111)
  • Events & Trending Topics (28)
  • IoT (Internet of Things) (387)
  • Java (1,247)
  • Kotlin (8)
  • Linux Administration (389)
  • Machine Learning (337)
  • MicroStrategy (6)
  • PMP (423)
  • Power BI (516)
  • Python (3,193)
  • RPA (650)
  • SalesForce (92)
  • Selenium (1,569)
  • Software Testing (56)
  • Tableau (608)
  • Talend (73)
  • TypeSript (124)
  • Web Development (3,002)
  • Ask us Anything! (66)
  • Others (2,231)
  • Mobile Development (395)
  • UI UX Design (24)

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

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

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 ‘replace’

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 ‘replace’” tells us that the list object we are handling does not have the replace attribute. We will raise this error if we try to call the replace() method on a list object. replace() is a string method that replaces a specified string with another specified string.

Python replace() Syntax

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

Parameters:

  • oldvalue: Required. The string value to search for within string
  • newvalue: Required. The string value to replace the old value
  • count: Optional. A number specifying how many times to replace the old value with the new value. The default is all occurrences

Let’s look at an example of calling the replace() method to remove leading white space from a string:

Now we will see what happens if we try to use the replace() method on a list:

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

Example #1: Using replace() on a List of Strings

Let’s look at an example list of strings containing descriptions of different cars. We want to use the replace() method to replace the phrase “car” with “bike”. Let’s look at the code:

Let’s run the code to get the result:

We can only call the replace() method on string objects. If we try to call replace() on a list, we will raise the AttributeError.

Solution

We can use list comprehension to iterate over each string and call the replace() method. Let’s look at the revised code:

List comprehension provides a concise, Pythonic way of accessing elements in a list and generating a new list based on a specified condition. In the above code, we create a new list of strings and replace every occurrence of “car” in each string with “bike”. Let’s run the code to get the result:

Example #2: Using split() then replace()

A common source of the error is the use of the split() method on a string prior to using replace(). The split() method returns a list of strings, not a string. Therefore if you want to perform any string operations you will have to iterate over the items in the list. Let’s look at an example:

We have a string that stores four names separated by commas. Three of the names are correct particle names and the last one “cheese” is not. We want to split the string using the comma separator and then replace the name “cheese” with “neutron”. Let’s look at the implementation that will raise an AttributeError:

Let’s run the code to see the result:

The error occurs because particles is a list object, not a string object:

Solution

We need to iterate over the items in the particles list and call the replace() method on each string to solve this error. Let’s look at the revised code:

In the above code, we create a new list of strings and replace every occurrence of “cheese” in each string with “neutron”. Let’s run the code to get the result:

Summary

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

The replace() function is suitable for string type objects. If you want to use the replace() method, ensure that you iterate over the items in the list of strings and call the replace 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 replace() method.

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

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.

Почему этот код .replace не работает, это может быть что-то с функцией def

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

Это работает нормально, но я не хочу печатать несколько строк (я делаю весь алфавит), например:

Как это. Я не хочу иметь несколько строк, я хочу сделать это в одной.

Я пытался использовать функцию def, чтобы понять это, но я запутался и совершенно застрял. Вот что у меня есть:

Я хочу, чтобы он вывел abc как! 1 @, но все, что я получил, это ошибка, вот она

3 ответа

Метод replace не работает на месте. Это означает, что вызов этого не изменит объект. Это то, что вы не можете сделать, потому что string объекты неизменны.

Вам нужно сделать message = message.replace(«a», «!») , а не просто message.replace(«a», «!») .

Кроме того, ваша функция должна return message , и тогда вы можете увидеть это, написав print(replacer(message)) (не print(replacer.message) ).

.replace() не работает без переназначения, потому что, как отмечали другие, строки неизменяемы. Лучше всего думать о .replace() как о функции, которая возвращает измененную строку, которая затем должна быть записана в переменную, вместо метода, доступного для строковых объектов. Например:

Без замены. Чтобы избежать этого, вам нужно переназначить переменную, такую как:

Далее, replacer не имеет атрибута .message , но это аргумент, который ожидает входную переменную , которую он назначит локальной переменной << X2>> (который скрывает вашу глобальную переменную message , что, вероятно, приводит к некоторой путанице. Обычно локальные и глобальные пространства имен должны отличаться!)

Наконец, ваша функция ничего не делает return . Я предлагаю вам ознакомиться с return инструкциями, чтобы узнать об этой функции.

Поэтому функциональный скрипт будет выглядеть так:

Запуск этого обновленного скрипта дает более подходящее:

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *