Split string but replace with another string and get list

python list replace
python replace character in string at index
string replace python
python replace multiple characters in string
replace function in list python
python string replace multiple
replace string in list python
list to string python

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?

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 :)

python, x = "HelloWorldHelloYou!" y = x.replace("Hello", "\nHey\n").lstrip("\n").split("\n") print(y) # ['Hey', 'World', 'Hey', 'You!'] This is a rather brute-force  While working with strings, one of the most used application is replacing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the replacement of a substring in list of string is performed. Let’s discuss certain ways in which this can be performed.

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!']

Python Strings: Replace, Join, Split, Reverse, Uppercase & Lowercase, Python String replace() :This tutorial covers Python String Operators; for slicing along with the index or indices to obtain a substring. The new value can be related to previous value or to a completely different string all together. Split strings is another function that can be applied in Python let see for  But wait a minute, above function splits a string by a character delimiter but what if I want to split it based on another string, like if first string is “Lets split this line using split functions” then on splitting it with “split” delimiter the result should be, “Lets”. “this line using”.

this functions can do it

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

Python, Here the replacement of a substring in list of string is performed. through the list and replace method replaces the section of substring with another. But this method is poor when it comes to performance than method above. Python | Tokenizing strings in list of strings · Python | Get the substring from given string using  Python Strings: Replace, Join, Split, Reverse, Uppercase & Lowercase. In Python everything is object and string are an object too. Python string can be created simply by enclosing characters in the double quote.

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']

Methods of RegExp and String, If we need positions of further matches, we should use other means, such as We can use it without regexps, to search and replace a substring: To find all hyphens, we need to use not the string "-" , but a regexp /-/g , with  Replace(String, String, Boolean, CultureInfo) Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string, using the provided culture and case sensitivity.

You can do this with iteration:

a=a.split(' ')
for word in a:
    if word=='Hello':
      a[a.index(word)]='Hey'

3 Ways To Replace All String Occurrences in JavaScript, You can replace all occurrences of a string using split and join approach, replace​() function replaceAll(string, search, replace) { return But '+' is an invalid regular expression, thus SyntaxError: Invalid regular expression: /+/ is thrown. Another approach would be to use String.prototype.replace() with a  dgvData.Rows.Clear() Dim myList1 As New List(Of String) myList1.AddRange(txtCompDataView.Lines) Dim row As String () For index = 0 To txtCompDataView.Lines.Count - 1 row = New String {myList1(index)} dgvData.Rows.Add(row) Next

Python String methods - split(), join() and replace(), This article covers python string methods split(), join() and replace() to join strings, i.e this method helps combine or concatenate strings but not like the + operator. to every element of an iterable or every character of another string. list of integers or non string type elements, we will get TypeError error. Java String replace() The java string replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence. Since JDK 1.5, a new replace() method is introduced, allowing you to replace a sequence of char values. There are two type of replace methods in java string.

C# Replace String Examples, Exchange all instances of one substring with another using Replace. Get the modified string. With StringBuilder, Replace works the same way as with strings, but we don't need to assign the result to anything. Here: In this example, we create  old – old substring you want to replace. new – new substring which would replace the old substring. count – the number of times you want to replace the old substring with the new substring. (Optional ) Return Value : It returns a copy of the string where all occurrences of a substring is replaced with another substring.

Python 3 Notes: Split and Join, For that, you need a different data type: a list of strings where each string corresponds to a word. But what if you want to split a string into a list of characters? Learn to split string by comma or space and store in array or arraylist. Use given Java program to convert string to List in Java. 1. Convert String to List Using Regular Expression. We can use regular expression "\\s*,\\s*" to match comma in CSV string and then do Java string split with String.split() method to convert string to list.

Comments
  • a = a.replace('Hello','Hey').split('Hey') would work.
  • This link here to what you do. stackoverflow.com/questions/2582138/…
  • @EdwardKotarski Its not working with HelloWorld!. I don't have spaces in my original data. These are just examples.
  • @WongSiwei I don't want loops etc to make my program complex.
  • You should be more specific where you want to separate the string then. Do you want to separate by space or by the first uppercase character?
  • 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
  • Downvoted because this is extremely overcomplicated and doesn't answer the question directly.