Tuesday 5 September 2017

Python Q & A

List to String

list1 = ['1', '2', '3']
str1 = ''.join(list1)  #123
Reverse the string
str1 = "Hi how are you"
print reversed(str1) #uoy era woh iH

To assign a string
str2 = "".join(reversed(str1)
print str2

Without using reversed function
def reverse_a_string(a_string):
    new_strings = []
    index = len(a_string)
    while index:
        index -= 1                       
        new_strings.append(a_string[index])
    return ''.join(new_strings)


Reverse the List
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];

aList.reverse();
print "List : ", aList  # ['xyz', 'abc', 'zara', 'xyz', 123]

No comments:

Post a Comment