Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to split a string by every nth separator in Python?

For example, if I had the following string:

"this-is-a-string"

Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?

like image 501
Gnuffo1 Avatar asked Oct 25 '09 19:10

Gnuffo1


People also ask

Can I split by multiple separators Python?

To split a string with multiple delimiters in Python, use the re. split() method. The re. split() function splits the string by each occurrence of the pattern.

How do you split a separator in Python?

Python String split() Method The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a string into an N in Python?

You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by newline character in Python, pass the newline character "\n" as a delimiter to the split() function.


1 Answers

Here’s another solution:

span = 2 words = "this-is-a-string".split("-") print ["-".join(words[i:i+span]) for i in range(0, len(words), span)] 
like image 53
Gumbo Avatar answered Sep 22 '22 17:09

Gumbo