-1

I have an array of strings, and would like to make some replacements. For example:

my_strings = [['hi / hello world &'], ['hi / hello world'], ['it\90s the world'], ['hello world'], ['hello "world"']]

new_strings = [['hi and hello world'], ['hi and hello world'], ["it's the world"], ['hello world'], ['hello world']]

How can I replace / with and, remove & and \90, and remove "" around words, if a string in the array contains these characters?

user2520932
  • 83
  • 2
  • 7
  • 2
    https://www.tutorialspoint.com/python/string_replace.htm – oshaiken Apr 13 '17 at 14:21
  • Take a look at the replace method in the official docs: https://docs.python.org/2/library/string.html – Haroldo_OK Apr 13 '17 at 14:22
  • Actually, you don't have an array of strings. Using your misnomer (it should be "list", not "array"), you have an array of arrays of strings. Is there any reason for the extra `[` and `]` around each string? – Scott Mermelstein Apr 13 '17 at 14:32

2 Answers2

2

Firstly you should create a dict object to map the word with it's replacement. For example:

my_replacement_dict = {
    "/": "and", 
    "&": "",   # Empty string to remove the word
    "\90": "", 
    "\"": ""
}

Then iterate over your list and replace the words based on above dict to get the desired list:

my_list = [['hi / hello world &'], ['hi / hello world'], ['it\90s the world'], ['hello world'], ['hello "world"']]
new_list = []

for sub_list in my_list:
    # Fetch string at `0`th index of nested list
    my_str = sub_list[0]   
    # iterate to get `key`, `value` from replacement dict
    for key, value in my_replacement_dict.items():  
         # replace `key` with `value` in the string
         my_str = my_str.replace(key, value)   
    new_list.append([my_str])   # `[..]` to add string within the `list` 

Final content of new_list will be:

>>> new_list
[['hi and hello world '], ['hi and hello world'], ['its the world'], ['hello world'], ['hello world']]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • Judging by OPs questions they might be new to python. Could you explain a little more detail in your code. For example explain why you are calling `sub_list[0]`. It might help OP to know that you are calling the index 0 of each sub list and why you are doing it. – Mike - SMT Apr 13 '17 at 14:35
  • @BaconTech Fair enough. Added the steps as comments – Moinuddin Quadri Apr 13 '17 at 14:41
0

As seen in that post : How to delete a character from a string using python?

You can use, for example, something like that

if "/" in my_string:
    new_string = my_string.replace("/", "and")

And include it in a loop over your whole array.

Community
  • 1
  • 1
fpiat
  • 23
  • 6