Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How exactly can you take a string, split it, reverse it and join it back together again?

How exactly can you take a string, split it, reverse it and join it back together again without the brackets, commas, etc. using python?

like image 907
Tstrmwarrior Avatar asked Sep 02 '10 12:09

Tstrmwarrior


People also ask

Does split return a string?

Using split()When the string is empty and no separator is specified, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.

What is the opposite of split in Python?

The inverse of the split method is join . You choose a desired separator string, (often called the glue) and join the list with the glue between each of the elements.

What happens when you split a string in Python?

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.


1 Answers

>>> tmp = "a,b,cde" >>> tmp2 = tmp.split(',') >>> tmp2.reverse() >>> "".join(tmp2) 'cdeba' 

or simpler:

>>> tmp = "a,b,cde" >>> ''.join(tmp.split(',')[::-1]) 'cdeba' 

The important parts here are the split function and the join function. To reverse the list you can use reverse(), which reverses the list in place or the slicing syntax [::-1] which returns a new, reversed list.

like image 142
Mad Scientist Avatar answered Oct 01 '22 12:10

Mad Scientist