0

I am trying to split a string but it should be replaced to another string and return as a list. Its hard to explain so here is an example:

I have string in variable a:

a = "Hello World!"

I want a list such that:

a.split("Hello").replace("Hey") == ["Hey"," World!"]

It means I want to split a string and write another string to that splited element in the list. SO if a is

a = "Hello World! Hello Everybody"

and I use something like a.split("Hello").replace("Hey") , then the output should be:

a = ["Hey"," World! ","Hey"," Everybody"]

How can I achieve this?

user10312797
  • 3
  • 1
  • 2

5 Answers5

1

From your examples it sounds a lot like you want to replace all occurrences of Hello with Hey and then split on spaces.

What you are currently doing can't work, because replace needs two arguments and it's a method of strings, not lists. When you split your string, you get a list.

>>> a = "Hello World!"
>>> a = a.replace("Hello", "Hey")
>>> a
'Hey World!'
>>> a.split(" ")
['Hey', 'World!']
Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74
0
x = "HelloWorldHelloYou!" 
y = x.replace("Hello", "\nHey\n").lstrip("\n").split("\n") 
print(y) # ['Hey', 'World', 'Hey', 'You!']

This is a rather brute-force approach, you can replace \n with any character you're not expecting to find in your string (or even something like XXXXX). The lstrip is to remove \n if your string starts with Hello.

Alternatively, there's regex :)

Melvin
  • 1,530
  • 11
  • 18
  • why would someone downvote this answer? It seems to be the best so far. well a bit of modification. try doing `x.replace("Hello", "\nHey\n").strip().split()` instead. This will split in spaces and line breaks too. Also it will do both stripping on both sides – Onyambu Sep 04 '18 at 04:39
0

this functions can do it

def replace_split(s, old, new):
    return sum([[blk, new for blk] in s.split(old)], [])[:-1]
0

It wasnt clear if you wanted to split by space or by uppercase.

import re    

#Replace all 'Hello' with 'Hey'

a = 'HelloWorldHelloEverybody'
a = a.replace('Hello', 'Hey')

#This will separate the string by uppercase character

re.findall('[A-Z][^A-Z]*', a) #['Hey', 'World' ,'Hey' ,'Everybody']
0

You can do this with iteration:

a=a.split(' ')
for word in a:
    if word=='Hello':
      a[a.index(word)]='Hey'
user70
  • 597
  • 2
  • 7
  • 24