• Stars
    star
    122
  • Rank 292,031 (Top 6 %)
  • Language
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

List of python tips

Python tips

List of python tips

  1. Use the Python 3 print function in Python 2
  2. Reverse a string or list
  3. Reverse by custom step
  4. List slice assignment
  5. Copy a list
  6. Create a list out of string
  7. Print elements of a list by unpacking (only Python 3)
  8. Check file or directory exists
  9. Call an external command
  10. Capture output from an external command
  11. Ternary conditional operator
  12. else in for loop
  13. Switch case
  14. Print to file
  15. Writing to file
  16. Reading from file
  17. Iterating over lines in a file
  18. Accessing attributes which start with underscores

Use the Python 3 print function in Python 2

# For Python 2, using the print() function from Python 3 helps future compatibility.
# It also allows better syntax when printing to files, or changing the line ending.
from __future__ import print_function

print('Python', 'Tips', sep='-', end='')
import sys
print('There was an error!', file=sys.stderr)
with open(filename, 'w') as f:
    print('Python!', file=f)

Reverse a string or list

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

my_string = "python"
print(my_string[::-1])
# output : nohtyp

Reverse by custom step

my_list = [1,2,3,4,5,6]
reverse_list = my_list[::-2]
print(reverse_list)
# output : [6,4,2]

List slice assignment

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

Copy a List

a = [1, 2, 3, 4]
''' Considered as one of the weirdest syntax to copy elements.'''
a_copy = a[:]

''' Another way of copying a list.'''
a_copy2 = list()
a_copy2.extend(a) # output a_copy2 = [1, 2, 3, 4]

Create a list out of string

data = "abcd"
data_list2 = list(data)  # OutPut: data_list = ['a', 'b', 'c', 'd'] 

Print elements of a list by unpacking (only Python 3)

my_list = [1, 2, 3, 4]
print(*my_list, sep='\t')   # Print elements of my_list separated by a tab

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 directory 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

pathlib.Path method (included in Python 3+, installable with pip for Python 2)

from pathlib import Path
Path(filename).exists()

Call an external command

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

Capture output from an external command

from subprocess import check_output
output = check_output(['ls', '/usr/bin'])

You can also capture stderr at the same time.

from subprocess import check_output, STDOUT, CalledProcessError
try:
    output = check_output(['ls', '/nonexistent'], stderr=STDOUT)
except CalledProcessError:
    print('Error: {}'.format(output.decode()))
else:
    print('Success: {}'.format(output.decode()))

Ternary conditional operator

print('True' if True else 'False')

else in for loop

An else block is executed if the loop body is not terminated by a break statement :

for i in range(5):
    print('Here we go!')
    if i == 2:
        break
else:
    print('There we went.')
# output : Here we go!
#          Here we go!
#          Here we go!

This for loop will get all the way to else:

for i in range(5):
    print('Here we go!')
    if i == 10:
        break
else:
    print('There we went.')
# output : Here we go!
#          Here we go!
#          Here we go!
#          Here we go!
#          Here we go!
#          There we went.

Switch Case

switcher = {
    1: "January",
    2: "February",
    3: "March",
    4: "April",
    5: "May",
    6: "June",
    7: "July",
    8: "August",
    9: "September",
    10: "October",
    11: "November",
    12: "December"
}
for i in range(1, 13):
    print(switcher.get(i, "Invalid month"))

Print to file

# Using `with` and `open`, the file will be closed when the `with` block finishes.
with open(filename, 'w') as outputfile:
    print('Python!', file=outputfile)

Writing to file

with open(filename, 'a') as outputfile:
    outputfile.write('Python!\n')

Reading from file

with open('file.txt', 'r') as inputfile:
    data = inputfile.read()

Iterating over lines in a file

When iterating over lines in a file, this method uses less memory because it reads one line at a time.

with open(filename, 'r') as inputfile:
    for line in inputfile:
        # Lines have a '\n' at the end, like inputfile.readlines().
        print(line, end='')

Accessing attributes which start with underscores

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

So to access attributes which start with underscores simply run obj_name._ClassName__attr_name .

class MyClass:

    def __init__(self):
        self.__private_attr = None

    def set_private_attr(self, attr_to_private):
        self.__private_attr = attr_to_private


attr = 7

my_class = MyClass()
my_class.set_private_attr(attr)

print(my_class._MyClass__private_attr)

📄 License

python-tips is MIT licensed, as found in the LICENSE file.

More Repositories

1

PyFladesk

create desktop application by using Flask and QtWebKit
Python
440
star
2

rust-youtube-downloader

Youtube video downloader written in Rust
Rust
158
star
3

PyFladesk-rss-reader

simple rss reader by PyFladesk
HTML
61
star
4

url-to-qrcode-firefox-addon

an add-on to convert current url to qr code !!
JavaScript
61
star
5

tg-bot-youtube-downloader

a telegram bot for download youtube videos.
PHP
48
star
6

chatgpt-toolbox

TypeScript
41
star
7

search-in-libgen

web extension to open search in LibGen from GoodReads
JavaScript
24
star
8

php-telegram-bot

a wrapper class for telegram bot api
PHP
22
star
9

php-telegram-cli

php wrapper for telegram cli
PHP
17
star
10

nodejs-online-users

Show online users on the map
JavaScript
14
star
11

english-learners-dictionary

English Learner's Dictionary Extension
JavaScript
13
star
12

youtube-video-info

Get the information such as caption, title, size, formats, etc. about a Youtube video
PHP
10
star
13

add-to-feedly

a firefox extension to add a website to feedly ;)
JavaScript
9
star
14

Artemis-Framework

MVC php Framework
PHP
8
star
15

aria2-qt-gui

a simple aria2 gui with Qt
C++
6
star
16

rtree

Directory tree structure written in Rust
Rust
6
star
17

php-youtube-downloader

Command line application for downloading Youtube videos
PHP
6
star
18

go-game-of-life

Conway's Game of life in Golang
Go
5
star
19

background-image-ckeditor-plugin

Plugin for set background image in CKEditor
JavaScript
5
star
20

pyqt-md-reader

simple PyQt app to read markdown format
Python
4
star
21

gouter

yet another go router
Go
3
star
22

Artemis-Framework2

Artemis Framework Version 2
PHP
3
star
23

php-whois

a class for get domain information
PHP
3
star
24

telegram-whois-bot

Telegram whois bot
PHP
2
star
25

hn-react-native

JavaScript
2
star
26

axel-downloader-for-firefox

a simple axel downloader extention for firefox
JavaScript
2
star
27

php-lambda-template

PHP
2
star
28

oxford-dictionary-scrapper

Python
2
star
29

dlr

(Not Yet) full feature CLI downloader written in Rust
Rust
2
star
30

blog

2
star
31

m3u-file-collector

collect all files in a m3u (playlist) file into a folder
Python
2
star
32

lbgndl

JavaScript
2
star
33

hn-classifier

Classification Hacker News posts
Python
1
star
34

dbman

Go
1
star
35

telegram-spotify-downloader

1
star
36

Loremipsum

ساخت متن لورم ایپسوم به زبان فارسی و انگلیسی با زبان برنامه نویسی php
PHP
1
star
37

UrlShortener

UrlShortener written in PHP
PHP
1
star
38

my-notes

1
star
39

keyboardsmash.github.io

My personal blog https://keyboardsmash.dev
HTML
1
star
40

go-filemanager

Go
1
star
41

PHProMVC

آموزش معماری سه لایه در PHP
PHP
1
star
42

laravel-nginx-installer

install laravel with nginx virtual host
Shell
1
star
43

wp-custom-register

create custom form for register , login and forgot password
PHP
1
star
44

api-platform-tmp

JavaScript
1
star
45

html5-games

simple html5 games
HTML
1
star
46

symfony-oxford-dictionary

PHP
1
star