How exactly can you take a string, split it, reverse it and join it back together again without the brackets, commas, etc. using python?
>>> 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.
Not fitting 100% to this particular question but if you want to split from the back you can do it like this:
theStringInQuestion[::-1].split('/', 1)[1][::-1]
This code splits once at symbol '/' from behind.
Do you mean like this?
import string
astr='a(b[c])d'
deleter=string.maketrans('()[]',' ')
print(astr.translate(deleter))
# a b c d
print(astr.translate(deleter).split())
# ['a', 'b', 'c', 'd']
print(list(reversed(astr.translate(deleter).split())))
# ['d', 'c', 'b', 'a']
print(' '.join(reversed(astr.translate(deleter).split())))
# d c b a
You mean this?
from string import punctuation, digits
takeout = punctuation + digits
turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis
I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-
def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
if string[y]==" ":
list_.append(string[x:y])
x = y+1
elif y==len(string)-1:
list_.append(string[x:y+1])
return list_
def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
reversed_list.append(element)
return reversed_list
def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with
space as a separator'''
final_string = str()
for element in list_:
final_string += str(element) + " "
return final_string
#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I
Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!
精彩评论