Skip to content

stuartcw/python-tips

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

Python tips

List of python tips

  1. Reverse a string or list
  2. Reverse by custom step
  3. List slice assignment
  4. Check file or directory exists
  5. Call an external command
  6. Ternary conditional operator

Reverse a string or list

list = ['a','b','c','d','e']
reverse_list = list[::-1]

string = "python"
print string[::-1]

Reverse by custom step

list = ['a','b','c','d','e']
reverse_list = list[::-2]

List slice assignment

  list = ['a','b','c','d','e']
  list[3:] = ['x','y','z']
  print list
  #output : ['a', 'b', 'c', 'x', 'y', 'z']

Check file or directory exists

os.path.isfile used only for files

import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if direcoty exists

os.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 exists

Call an external command

from subprocess import call
call(['ls,'-l'])

Ternary conditional operator

print 'True' if True else 'False'

About

List of python tips

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published