Split string by separators [duplicate] - python

This question already has answers here:
Split string based on regex
(3 answers)
Closed 2 years ago.
I'm try to split text from string, but I can't.
I have 1;2 | 2;4, for example in my string, and I want to:
['1;2', '|', '2;4']

You can use str.partition:
>>> '1;2 | 2;4'.partition("|")
('1;2 ', '|', ' 2;4')

Related

How to delete certain words from string without spaces? [duplicate]

This question already has answers here:
How to remove substring from string in Python 3
(2 answers)
Closed 2 years ago.
Is there I way to delete words from a string in Python if it doesn't have spaces. For example, if you have the string "WUBHELLOWUB" I want to remove "WUB". I tried
s = 'WUBHELLOWUB'
while 'WUB' in s:
ind = s.find('WUB')
s = s[:ind] + s[ind+1:]
print(s)
but it did not work.
You can use regex
import re
data=r"\S*WUB\S*"
re.sub(data, '','WUBWUBHELLO')

regex split to split a string [duplicate]

This question already has answers here:
What is a non-capturing group in regular expressions?
(18 answers)
the output of re.split in python doesn't make sense to me
(3 answers)
Closed 2 years ago.
I need to split "WUBWUBIWUBAMWUBWUBX" such that I get the words ['I','AM','X']
I tried using this line:
l=re.split("([W][U][B])+","WUBWUBIWUBAMWUBWUBX")
I got the output like :
['', 'WUB', 'I', 'WUB', 'AM', 'WUB', 'X']

How can I give spaces while joining 2 strings together? [duplicate]

This question already has answers here:
How do I convert a list into a string with spaces in Python?
(6 answers)
Closed 2 years ago.
As I join 2 strings like:
print("not" + "X")
The result is like this:
notX
How could I make this into:
not X
Try using:
print("not","X")
# or:
' '.join(i for i in ['not','X'])
# or:
' '.join(('not','X'))
instead of:
print("not"+"X")

converting a string to a readable sentence [duplicate]

This question already has answers here:
How do I convert a list into a string with spaces in Python?
(6 answers)
Closed 4 years ago.
say you have a list like so:
lst = ['my', 'name', 'is', 'jack.']
If I convert to a string doing this:
''.join(lst)
output
'mynameisjack.'
How do I make the list print out:
"my name is jack."
instead of all together.
Instead of using ''.join(lst)(an empty string), use ' '.join(lst), with a space (see the documentation of join!).

How can I split a pipe-separated string into a list? [duplicate]

This question already has answers here:
Split a string by a delimiter in python
(5 answers)
Closed 3 years ago.
I have this string:
var(HELLO,)|var(Hello again)| var(HOW ARE YOU?)|outV(0)|outV(1)|outV(2)|END
I want to split it on the |. I don't want it to split at the white space, only at the |.
Is this possible?
The way to do this is clearly documented here.
Example:
>>> myString = "subString1|substring2|subString3"
>>> myString = myString.split("|")
>>> print myString
["subString1", "subString2", "subString3"]

Categories