List of python tips
- Reverse a string or list
- Reverse by custom step
- List slice assignment
- Copy a list
- Create a list out of string
- Check file or directory exists
- Call an external command
- Ternary conditional operator
- for else
my_list = ['a','b','c','d','e']
reverse_list = my_list[::-1]
my_string = "python"
print my_string[::-1]my_list = [1,2,3,4,5,6]
reverse_list = my_list[::-2]
# output : [6,4,2] my_list = ['a','b','c','d','e']
my_list[3:] = ['x','y','z']
print my_list
#output : ['a', 'b', 'c', 'x', 'y', 'z']a = [1, 2, 3, 4]
''' Considered as one of the weirdest syntax to copy elements.'''
a_copy = a[:]data = "abcd"
data_list2 = list(data) # OutPut: data_list = ['a', 'b', 'c', 'd'] os.path.isfile used only for files
import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory existsos.path.exists used for both files and directories
import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) #True if directory existsfrom subprocess import call
call(['ls,'-l'])print 'True' if True else 'False'my_string = ""
for i in my_string:
print i
else :
print 'String is empty'