# Help with replace()

**URL:** <https://discuss.python.org/t/help-with-replace/17501>\
**Category:** Python Help\
**Tags:** help\
**Created:** [July 20, 2022, 11:48am UTC](https://discuss.python.org/t/help-with-replace/17501 "2022-07-20T11:48:55Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Moez](https://avatars.discourse-cdn.com/v4/letter/m/ed655f/32.png) [@Moez](https://discuss.python.org/u/Moez)\
**Post date:** [July 20, 2022, 11:48am UTC](https://discuss.python.org/t/help-with-replace/17501/1 "2022-07-20T11:48:56Z")

</div>

lst = [‘company1\_hat’, ‘company1\_glasses’, ‘company2\_hat’]  
nlst = [el.replace(‘\_’, ‘', '’) for el in lst]  
print(nlst)  
the output:

```auto
['company1", "hat', 'company1", "glasses', 'company2", "hat']

```

the desired output:

```auto
['company1', 'hat', 'company1', 'glasses', 'company2', 'hat']

```

---

<div class="post-metadata">

**Author:** ![vainaixr](https://avatars.discourse-cdn.com/v4/letter/v/5f8ce5/32.png) [@vainaixr](https://discuss.python.org/u/vainaixr)\
**Post date:** [July 20, 2022, 12:14pm UTC](https://discuss.python.org/t/help-with-replace/17501/2 "2022-07-20T12:14:28Z")

</div>

could use split here,

```auto
nlst = []
for i in lst:
  nlst += i.split('_')
nlst

```

→

```auto
['company1', 'hat', 'company1', 'glasses', 'company2', 'hat']

```

---

<div class="post-metadata">

**Author:** ![Moez](https://avatars.discourse-cdn.com/v4/letter/m/ed655f/32.png) [@Moez](https://discuss.python.org/u/Moez)\
**Post date:** [July 20, 2022, 12:17pm UTC](https://discuss.python.org/t/help-with-replace/17501/3 "2022-07-20T12:17:15Z")

</div>

@vainaixr thank you dude

---

<div class="post-metadata">

**Author:** ![vainaixr](https://avatars.discourse-cdn.com/v4/letter/v/5f8ce5/32.png) [@vainaixr](https://discuss.python.org/u/vainaixr)\
**Post date:** [July 20, 2022, 12:19pm UTC](https://discuss.python.org/t/help-with-replace/17501/4 "2022-07-20T12:19:51Z")

</div>

one more way to do this is,

```auto
[nlst := nlst + i.split('_') for i in lst]

```

---

<div class="post-metadata">

**Author:** ![vbrozik](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/vbrozik/32/7423_2.png) [@vbrozik](https://discuss.python.org/u/vbrozik)\
**Post date:** [July 20, 2022, 12:35pm UTC](https://discuss.python.org/t/help-with-replace/17501/5 "2022-07-20T12:35:36Z")

</div>

…and one more - pure functional approach:

```python
import itertools

lst = ['company1_hat', 'company1_glasses', 'company2_hat']

split_pairs = (item.split('_') for item in lst)
split_items = itertools.chain.from_iterable(split_pairs)

list(split_items)

```

Split to two expressions for better readability.

Note to the original code: You want to create a different number of strings. This cannot be done by using `str.replace()` because this function changes a string to a different string. This function cannot split or join strings which would be needed to change their number.

---

<div class="post-metadata">

**Author:** ![Moez](https://avatars.discourse-cdn.com/v4/letter/m/ed655f/32.png) [@Moez](https://discuss.python.org/u/Moez)\
**Post date:** [July 20, 2022, 12:43pm UTC](https://discuss.python.org/t/help-with-replace/17501/6 "2022-07-20T12:43:06Z")

</div>

ok, one more question:  
originally I got the idea to split list elements with the ‘\_’ character because I needed to convert it to a dict and then compare it to another list like so:

```auto
first list = [“company1_hat”, “company1_glasses”, “company2_hat”]
second list = [“hat”, “glasses”]

```

so the question is how to determine which company has a missed item from the second list ?  
So the result will be campany2 here for example

---

<div class="post-metadata">

**Author:** ![vbrozik](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/vbrozik/32/7423_2.png) [@vbrozik](https://discuss.python.org/u/vbrozik)\
**Post date:** [July 20, 2022, 1:26pm UTC](https://discuss.python.org/t/help-with-replace/17501/7 "2022-07-20T13:26:44Z")

</div>

This will create dictionary of sets which is suitable for the task:

```python
lst = ['company1_hat', 'company1_glasses', 'company2_hat']

split_pairs = (item.split('_') for item in lst)
companies_items = {}
for company, item in split_pairs:
    company_items = companies_items.setdefault(company, set())
    company_items.add(item)

print(companies_items)

```

```python
{'company1': {'hat', 'glasses'}, 'company2': {'hat'}}

```

The rest is up to you. Show us the result please.

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [July 20, 2022, 1:42pm UTC](https://discuss.python.org/t/help-with-replace/17501/9 "2022-07-20T13:42:30Z")

</div>

This is sort of a quickly hammered out solution, but you’ll earn your stripes by parsing through the loops, @Moez.

Comparing to Václav’s split generator and dictionary-based approach, the benefits of choosing the optimal data type are very obvious. And I obviously ought to learn more about Python sets and dictionaries.

```auto
compositeList = ['company1_hat', 'company1_glasses', 'company2_hat']
itemList = ['hat', 'glasses']
companyList = []
nameList = []
inventory = []

for member in compositeList:
    nam = member[:member.find('_')]
    if nam not in nameList:
        #build a list of companies
        nameList.append(nam)

for company in nameList:
    for composite in compositeList:
        if company not in composite: continue
        #build a list of this comany's items
        inventory.append(composite[composite.find('_')+1:])
    for item in itemList:
        #does this company have this item?
        if item not in inventory:
            print(f"{company} is missing {item}")
    inventory = []

```

OUTPUT:

> company2 is missing glasses

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [July 20, 2022, 2:10pm UTC](https://discuss.python.org/t/help-with-replace/17501/10 "2022-07-20T14:10:00Z")

</div>

> [@vbrozik](#):
>
> ```python
> company_items = companies_items.setdefault(company, set())
> company_items.add(item)
> 
> ```

Václav, would you mind explaining how adding a member to the `company_items` set appends to the set inside of the `companies_items` dictionary?

---

<div class="post-metadata">

**Author:** ![vbrozik](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/vbrozik/32/7423_2.png) [@vbrozik](https://discuss.python.org/u/vbrozik)\
**Post date:** [July 20, 2022, 2:26pm UTC](https://discuss.python.org/t/help-with-replace/17501/11 "2022-07-20T14:26:00Z")

</div>

The dictionary `companies_items` has companies as keys, and sets of items as values.

This gets the set of items for the given `company`. If the `company` does not exist in the dictionary yet, it adds it and initializes the value to an empty set: `set()`.

```auto
    company_items = companies_items.setdefault(company, set())

```

Now `company_items` always contains either an existing set or a freshly created empty set and we can simply add the item:

```auto
    company_items.add(item)

```

* * *

Note that in the standard library there is also: [collections.defaultdict](https://docs.python.org/3/library/collections.html#collections.defaultdict) with which you could squeeze the two statements into: `companies_items[company].add(item)`.

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [July 20, 2022, 2:35pm UTC](https://discuss.python.org/t/help-with-replace/17501/12 "2022-07-20T14:35:41Z")

</div>

> [@vbrozik](#):
>
> This gets the set of items for the given `company` .

How did you know this? When I looked up `<dict>.setdefault()`, in [**docs.python**](https://docs.python.org/3/library/stdtypes.html?highlight=setdefault#dict.setdefault) it only has a very short statement about what `setdefault()` returns if the key does or does not exist. It said nothing about creating an object reference to the value in the dictionary.

This is the entire entry:

> `setdefault` (_key_ [, _default_])  
> If _key_ is in the dictionary, return its value. If not, insert _key_ with a value of _default_ and return _default_. _default_ defaults to `None`.

I guess what’s not clear from this entry is that it returns a _ **reference** _ to the _value_. I imagined that it was returning the value _as a value_ (speaking in terms of passing by reference or passing by value).

---

<div class="post-metadata">

**Author:** ![vbrozik](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/vbrozik/32/7423_2.png) [@vbrozik](https://discuss.python.org/u/vbrozik)\
**Post date:** [July 20, 2022, 2:53pm UTC](https://discuss.python.org/t/help-with-replace/17501/13 "2022-07-20T14:53:57Z")

</div>

> [@mlgtechuser](#):
>
> passing by reference or passing by value

In Python every variable is a reference to an object. You cannot pass by value in Python.

I imagine it like an object must first exist then you assign a variable to it. A variable is like a label through which you can work with the object which still exists at the same place in memory. You do not pass it by value (by copying it).

If you use an immutable type - for example string:

```python
    company_items = companies_items.setdefault(company, '')

```

Then the following code is pointless because it just changes the variable `company_items` to point to a newly created string and the dictionary value would still point to the empty string.

```python
    company_items += item

```

You can change dictionary values through `get()` or `setdefault()` only through their mutation in-place. They must be of a mutable type to be able to do this.

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [July 20, 2022, 3:25pm UTC](https://discuss.python.org/t/help-with-replace/17501/14 "2022-07-20T15:25:41Z")

</div>

> [@vbrozik](#):
>
> You do not pass it by value (by copying it).

Yes, I realize that now and know intellectually that “in Python, (almost) everything is an object.”

‘key : value’ is an unfortunate choice of terms. I have only used dictionaries for string and integer lookups for information purposes so far, not for object manipulation. Because of this, I was still applying the common definition of “value”.

‘key : item’ would be better, but ‘key : value’ is very embedded now.

---

<div class="post-metadata">

**Author:** ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)\
**Post date:** [July 20, 2022, 3:54pm UTC](https://discuss.python.org/t/help-with-replace/17501/15 "2022-07-20T15:54:47Z")

</div>

You cannot pass by reference in Python either.

Pass by reference has a precise meaning, going back to Pascal in the 1970s and possibly as far back as Fortran in the 1950s.

The fundamental test for pass by reference semantics is to write a swap _procedure_ which accepts any two variables, and swaps their values:

```
a = 1
b = 2
swap(a, b)
assert a == 2 and b == 1

```

Note the conditions: the names of the variables are not hard-coded, they can be any variable. The swap procedure does not return anything, it operates purely by side-effect.

You cannot write this swap() procedure in Python.

Python does not use “pass by reference” (or “call by reference”) semantics. Like many other languages, it uses parameter passing semantics which unfortunately [goes by many names](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing):

- pass by object
- pass by object reference
- pass by object sharing
- pass by sharing

Java, in particular, abuses the terminology by calling it “pass by value”, using the “logic” that given some variable:

```
x = 2

```

(say), the _actual_ value of the variable, which the compiler copies to pass to a function, is not 2, but some invisible, untouchable machine address like 395632077210.

As the Python luminary the late Fredrik Lundh (the Effbot) wrote:

> [@](#):
>
> Well, I guess you can, in theory, value an artificial number assigned to an object as much as the object itself.
> 
> “Joe, I think our son might be lost in the woods”
> 
> “Don’t worry, I have his social security number”

---

<div class="post-metadata">

**Author:** ![Moez](https://avatars.discourse-cdn.com/v4/letter/m/ed655f/32.png) [@Moez](https://discuss.python.org/u/Moez)\
**Post date:** [July 22, 2022, 9:05am UTC](https://discuss.python.org/t/help-with-replace/17501/16 "2022-07-22T09:05:32Z")

</div>

Hi @mlgtechuser, I test the code it works fine but I changed it a little bit so it returns either the company name or ‘N/A’, so I wrote:

```auto
for company in nameList:
        for composite in uniformPieces:
            if company not in composite:
                continue
            #build a list of this comany's items
            inventory.append(composite[composite.find('_')+1:])
        for item in uniformSet:
            #does this company have this item?
            if item not in inventory:
                a = f"{company}"
                return a
        inventory = ['N/A']
        inventory[0]

```

the output remains fine nut only for the first case which is the company name, how to return N/A?

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [July 22, 2022, 10:29am UTC](https://discuss.python.org/t/help-with-replace/17501/17 "2022-07-22T10:29:18Z")

</div>

> [@Moez](#):
>
> ```python
> inventory = ['N/A']
> inventory[0]
> 
> ```

The last line in the nameList loop clears out the inventory for the next company, so it needs to be `inventory = []` or `inventory.clear()`.

What conditions apply to “N/A”?

---

<div class="post-metadata">

**Author:** ![Moez](https://avatars.discourse-cdn.com/v4/letter/m/ed655f/32.png) [@Moez](https://discuss.python.org/u/Moez)\
**Post date:** [July 22, 2022, 10:31am UTC](https://discuss.python.org/t/help-with-replace/17501/18 "2022-07-22T10:31:02Z")

</div>

the condition applies to ‘N/A’ if there’s no company has a missed component

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [July 22, 2022, 10:39am UTC](https://discuss.python.org/t/help-with-replace/17501/19 "2022-07-22T10:39:14Z")

</div>

Ah. I didn’t see that in the Software Specification. 😉

How you capture the “company has all items” condition depends on what you’re planning to do with the data later, of course. What are you planning to do with “company X has all items”?

BTW, &nbsp;`a = f"{company}"` &nbsp;is equivalent to &nbsp;`a = company` &nbsp;since `company` is already a string.

> [@Moez](#):
>
> ‘N/A’ if there’s no company has a missed component

If _ALL_ companies have _ALL_ items?

---

<div class="post-metadata">

**Author:** ![Moez](https://avatars.discourse-cdn.com/v4/letter/m/ed655f/32.png) [@Moez](https://discuss.python.org/u/Moez)\
**Post date:** [July 22, 2022, 10:41am UTC](https://discuss.python.org/t/help-with-replace/17501/20 "2022-07-22T10:41:16Z")

</div>

just return ‘N/A’ or ‘OK’ in case all companies have all items otherwise, the company name which has one or more missing components

---

<div class="post-metadata">

**Author:** ![mlgtechuser](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mlgtechuser/32/7310_2.png) [@mlgtechuser](https://discuss.python.org/u/mlgtechuser)\
**Post date:** [July 22, 2022, 10:44am UTC](https://discuss.python.org/t/help-with-replace/17501/21 "2022-07-22T10:44:54Z")

</div>

Okay. You can use a conditional output message for that:

Set &nbsp;`msgOut = "All companies have all items."`&nbsp; before the `company in nameList:` loop.

…and in the &nbsp;`if item not in inventory:`&nbsp; section, set the message to empty string (`''`). You can print the msgOut unconditionally since it will be `''` if a company is missing an item.

[Next page](https://discuss.python.org/t/help-with-replace/17501.md?page=2)
