MJay

Useful Python Commands 본문

Programming/Python

Useful Python Commands

MJSon 2019. 3. 24. 21:32

Python Basics

print ('Alice' * 5) 'AliceAliceAliceAliceAlice'

Flow Control

spam = ['cat', 'bat', 'rat', 'elephant'] spam[0:4] ['cat', 'bat', 'rat', 'elephant'] spam[1:3] ['bat', 'rat'] spam[0:-1] ['cat', 'bat', 'rat']

Changing Values in a List with Indexes

spam = ['cat', 'bat', 'rat', 'elephant'] spam[1] = 'aardvark' spam ['cat', 'aardvark', 'rat', 'elephant'] spam[2] = spam[1] spam ['cat', 'aardvark', 'aardvark', 'elephant'] spam[-1] = 12345 spam ['cat', 'aardvark', 'aardvark', 12345]

The copy Module’s copy() and deepcopy() Functions

Although passing around references is often the handiest way to deal with lists and dictionaries, if the function modifies the list or dictionary that is passed, you may not want these changes in the original list or dictionary value. For this, Python provides a module named copy that provides both the copy() and deepcopy() functions. The first of these, copy.copy(), can be used to make a duplicate copy of a mutable value like a list or dictionary, not just a copy of a reference. Enter the following into the interactive shell:

import copy spam = ['A', 'B', 'C', 'D'] cheese = copy.copy(spam) cheese[1] = 42 spam ['A', 'B', 'C', 'D'] cheese ['A', 42, 'C', 'D']

Dictionary

get() Method

picnicItems = {'apples': 5, 'cups': 2} 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.' 'I am bringing 2 cups.' 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.' 'I am bringing 0 eggs.'

The setdefault() Method

spam = {'name': 'Pooka', 'age': 5} spam.setdefault('color', 'black') 'black' spam {'color': 'black', 'age': 5, 'name': 'Pooka'} spam.setdefault('color', 'white') 'black' spam {'color': 'black', 'age': 5, 'name': 'Pooka'}

Wordcount Example and Pretty Priting

import pprint
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}

for character in message:
    count.setdefault(character, 0)
    count[character] = count[character] + 1

pprint.pprint(count)

Escaoe Characters

spam = 'Say hi to Bob\'s mother.'

Raw Strings

RAW STRINGS You can place an r before the beginning quotation mark of a string to make it a raw string. A raw string completely ignores all escape characters and prints any backslash that appears in the string. For example, type the following into the interactive shell:

>>> print(r'That is Carol\'s cat.')
That is Carol\'s cat.

Multiple Strings with triple quotes

print('''Dear Alice,

Eve's cat has been arrested for catnapping, cat burglary, and extortion.

Sincerely,
Bob''')

The join() and split() String Methods

>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'

Justifying Text with rjust(), ljust(), and center()

>>> 'Hello'.rjust(10)
'     Hello'
>>> 'Hello'.rjust(20)
'               Hello'
>>> 'Hello World'.rjust(20)
'         Hello World'
>>> 'Hello'.ljust(10)
'Hello'
>>> 'Hello'.rjust(20, '*')
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello---------------'
>>> 'Hello'.center(20)
'       Hello       '
>>> 'Hello'.center(20, '=')
'=======Hello========'

Copying and Pasting Strings with the pyperclip Module’s

>>> import pyperclip
>>> pyperclip.copy('Hello world!')
>>> pyperclip.paste()
'Hello world!'

Finding Patterns of Text with Regular Expressions

Regular expressions, called regexes for short, are descriptions for a pattern of text. For example, a \d in a regex stands for a digit character—that is, any single numeral 0 to 9. The regex \d\d\d-\d\d\d-\d\d\d\d is used by Python to match the same text the previous isPhoneNumber() function did: a string of three numbers, a hyphen, three more numbers, another hyphen, and four numbers. Any other string would not match the \d\d\d-\d\d\d-\d\d \d\d regex.

But regular expressions can be much more sophisticated. For example, adding a 3 in curly brackets ({3}) after a pattern is like saying, “Match this pattern three times.” So the slightly shorter regex \d{3}-\d{3}-\d{4} also matches the correct phone number format.

Creating Regex Objects

All the regex functions in Python are in the re module. Enter the following into the interactive shell to import this module:

import re

Passing a string value representing your regular expression to re.compile() returns a Regex pattern object (or simply, a Regex object).

To create a Regex object that matches the phone number pattern, enter the following into the interactive shell. (Remember that \d means “a digit character” and \d\d\d-\d\d\d-\d\d\d\d is the regular expression for the correct phone number pattern.)

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
# raw strings

Matching Regex Objects

A Regex object’s search() method searches the string it is passed for any matches to the regex. The search() method will return None if the regex pattern is not found in the string. If the pattern is found, the search() method returns a Match object. Match objects have a group() method that will return the actual matched text from the searched string. (I’ll explain groups shortly.) For example, enter the following into the interactive shell:

>>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
>>> mo = phoneNumRegex.search('My number is 415-555-4242.')
>>> print('Phone number found: ' + mo.group())
Phone number found: 415-555-4242

The mo variable name is just a generic name to use for Match objects. This example might seem complicated at first, but it is much shorter than the earlier isPhoneNumber.py program and does the same thing.

Here, we pass our desired pattern to re.compile() and store the resulting Regex object in phoneNumRegex. Then we call search() on phoneNumRegex and pass search() the string we want to search for a match. The result of the search gets stored in the variable mo. In this example, we know that our pattern will be found in the string, so we know that a Match object will be returned. Knowing that mo contains a Match object and not the null value None, we can call group() on mo to return the match. Writing mo.group() inside our print statement displays the whole match, 415-555-4242.

Review of Regular Expression Matching

While there are several steps to using regular expressions in Python, each step is fairly simple.

Import the regex module with import re.

Create a Regex object with the re.compile() function. (Remember to use a raw string.)

Pass the string you want to search into the Regex object’s search() method. This returns a Match object.

Call the Match object’s group() method to return a string of the actual matched text.