0% found this document useful (0 votes)
29 views23 pages

Python String Basics and Usage

Uploaded by

I Am
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views23 pages

Python String Basics and Usage

Uploaded by

I Am
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON STRING

Ph.D. / Golden Gate


Ave, San Francisco /
Seoul National Univ /
Carnegie Mellon / UC
Berkeley / DevOps /
Deep Learning /
([Link] Visualization

v=250&username=khhong7)
Sponsor Open Source
development
activities and free
contents for

[Link] site search: everyone.

Custom Search Search

Thank you.

Python string - K Hong


([Link]

Python has two build-in types of strings: str


holds bytes, and unicode holds Unicode
characters. If we only deal with 7-bit ASCII
characters (characters in the range of 0-
127), we can save some memory by using
strs. However, we should be careful if we
use an 8-bit character set. In general, it is
not always possible simply by examining the
bytes to determine which 8-bit encoding is
used for a particular string. But the safest
way is to use strs for 7-bit ASCII and for raw
binary 8-bit bytes, and unicode otherwise.

Note: Good news is that Python 3.x doesn't


have a special Unicode string type/class.
Every string is a Unicode string.
String Literals
Python strings are fairly easy to use. But
there are so many ways to write them in our
code:

Python
tutoria

Python
Home
([Link]

Introduction
([Link]

Running
Python
Programs
(os, sys,
import)
([Link]
Modules
>>> # Single quotes
and IDLE
>>> print('P"casso')
P"casso
(Import,
Reload,
>>> # Double quotes exec)
>>> print("P'casso") ([Link]
P'casso

Object
>>> # Tripple quotes Types -
>>> print('''...Picasso...''')
Numbers,
...Picasso...
Strings, and
>>> # Escape sequences None
>>> print("P\ti\nca\Osso") ([Link]
P i
ca\Osso
Strings -
Escape
>>> #Raw strings
>>> print(r"C:\[Link]") Sequence,
C:\[Link] Raw String,
and Slicing
>>> # Byte strings ([Link]
>>> print(b'Picas\x01so')
b'Picas\x01so'
>>> type(b'Picas\x01so') Strings -
<class 'bytes'> Methods
>>> type('normal_string') ([Link]
<class 'str'>
>>> # Unicode strings Formatting
>>> S = 'A\u00c4B\U000000e8C' Strings -
>>> S
expressions
'A-B-C'
>>> len(S) and method
5 calls
>>> ([Link]

Files and
[Link]
([Link]

Quoted Strings Traversing


Single and double quote characters are the directories
recursively
same.
([Link]

>>> 'Picasso', "Picasso"


Subprocess
('Picasso', 'Picasso') Module
([Link]

The reason for supporting both is that it


Regular
allows us to embed a quote character of the Expressions
other variety inside a string without with Python
escaping it with a backslash. ([Link]
Object
>>> 'Mozart"s', "Mozart's"
Types - Lists
('Mozart"s', "Mozart's")
([Link]

Python concatenates adjacent string literals Object


in any expression. Types -
Dictionaries
and Tuples
>>> masters = "Mozart " 'and' " Picass ([Link]
>>> masters
'Mozart and Picasso'
Functions
def, *args,
If we add commas between these strings, **kargs
we'll have a tuple not a string. ([Link]

Functions
>>> "Mozart\"s", 'Picasso\'s' lambda
('Mozart"s', "Picasso's") ([Link]

Built-in
Functions
([Link]

map, lter,
Escape Sequences and reduce
A backslash is representative of a general ([Link]
pattern in strings. Backslashes are used to
introduce special byte coding, escape Decorators
([Link]
sequences.

List
Escape sequences let us embed byte codes Comprehensi
in strings that cannot easily be type on a ([Link]
keyboard. The character \, and one or more
characters following it in the string literal, Sets
are replaced with a single character in the (union/interse
and
resulting string object. The object has the
itertools -
binary value speci ed by the sequence. For
Jaccard
instance, here is a ve-character string that
coe cient
embeds a newline and a tab: and
shingling to
check
>>> s = 'a\nb\tc'
plagiarism
([Link]
The two characters \n stand for a single
character - the byte containing the binary Hashing
value of the newline character in our (Hash tables
character set which is ASCII code 10. The and hashlib)
([Link]
sequence \t is replaced with the tab
character. The way this string looks when
printed depends on how we print it. While Dictionary
the interactive echo shows the special Comprehensi
with zip
characters as escapes, but print interprets
([Link]
them instead:

The yield
keyword
>>> s
'a\nb\tc' ([Link]
>>> print(s)
a Generator
b c Functions
and
We can check how many characters are in Expressions
the string. ([Link]

[Link]
>>> len(s) method
5 ([Link]

Iterators
So, the string is ve bytes long. It contains
([Link]
an ASCII a, a new line, an ASCII b, etc. The
backslash characters are not really stored
Classes and
with the string in memory. They are just Instances
used to tell Python to store special byte (__init__,
values in the string. Here are string __call__, etc.)
backslash characters: ([Link]

if__name__
Escape Meaning ==
'__main__'
\newline Ignored (continuation line) ([Link]
\\ Backslash (stores one \)
argparse
\' Single quotes (stores ')
([Link]
\" Double quotes (stores ")

\a Bell Exceptions
([Link]
\b Backspace

\f Formfeed @static
\n Newline (linefeed) method vs
class
\r Carriage return
method
\t Horizontal tab ([Link]
\v Vertical tab
Private
Character with hex value hh (at
\xhh attributes
most 2 digits)
and private
methods
Character with octal value ooo ([Link]
\ooo
(up to 3 digits)
bits, bytes,
Null: binary 0 character (doesn't
\0 bitstring,
end string)
and
\N{ id } Unicode database ID
constBitStrea
\uhhhh Unicode 16-bit hex ([Link]
\Uhhhhhhhh Unicode 32-bit hex
[Link](s)
Not an escape (keeps both \ and
\other and
other)
[Link](s)
Some escape sequences allow us to embed
([Link]
binary values into the bytes of a string. Here json-
we have ve-character string with two dumps-
binary zeros: loads- le-
read-
[Link])
>>> s = 'A\0B\0C'
>>> s Python
'A\x00B\x00C'
Object
Serialization
The zero(null) byte does not terminate a - pickle and
string. Instead, Python keeps the string's json
length and text in memory. Here we have a ([Link]
string with a binary 1 and 2 (in octal) and 3 Python
(hexa): Object
Serialization
- yaml and
>>> s = '\001\002\x03' json
>>> s ([Link]
'\x01\x02\x03'
>>> len(s)
Priority
3
queue and
heap queue
Here, Python prints out nonprintable data
characters in hex, regardless of how they structure
are speci ed. Here we have "Picasso", a tab, ([Link]
a newline, and a zero value coded in hex:
Graph data
structure
>>> s = "Pi\tcc\nas\x00so" ([Link]
>>> s
'Pi\tcc\nas\x00so' Dijkstra's
>>> print(s)
shortest
Pi cc
as path
algorithm
([Link]

Prim's
If Python does not recognize the character spanning
after a backslash (\) as an escape code, it tree
simply keeps the backslash in the string: algorithm
([Link]

>>> x = "Picas\so" Closure


>>> x ([Link]
'Picas\\so'
>>> len(x) Functional
8
programming
in Python
([Link]
As memtioned before, Python 3.x doesn't
have a special Unicode string type/class, and Remote
very string is a Unicode string. So, we do not running a
need to use unichr() any more, we can just local le
using ssh
use chr() as in the example below.
([Link]

>>> uro = chr(8364) SQLite 3 - A.


>>> euro Connecting
€ to DB,
>>> ord(euro) create/drop
8364
table, and
>>>
insert data
into a table
([Link]

SQLite 3 - B.
Raw String with Escape Selecting,
Sequences updating
and deleting
Let's look at the following code for opening
data
a le:
([Link]

MongoDB
>>> myfile = open('C:\new\[Link]', '
Traceback (most recent call last):
with
File ... PyMongo I -
myfile = open('C:\new\[Link]', ' Installing
IOError: [Errno 22] Invalid argument: MongoDB ...
([Link]
The problem is that \n is considered as a
newline character, and \t as a tab. This is Python
HTTP Web
where raw strings can do something. If the
Services -
letter r (uppercase or lowercase) appears
urllib,
before the opening quote of a string, it httplib2
suppresses the escape mechanism. The ([Link]
result is that Python keeps our backslash
literally. In other words, backslashes are not Web
handled in any special way in a string literal scraping
pre xed with 'r'. So r"\n" is a two-character with
string containing '\' and 'n', while "\n" is a Selenium
for checking
one-character string containing a newline.
domain
Usually patterns will be expressed in Python
availability
code using this raw string notation. ([Link]

So, to x the lename problem, we can just REST API :


add the letter r: Http
Requests
for Humans
>>> myfile = open(r'C:\new\[Link]', with Flask
([Link]
REST-API-
Or, since two backslashes are really an
Http-
escape sequence for one backslash, we can
Requests-
keep our backslash by doubling them:
for-
Humans-
with-
>>> myfile = open('C:\\new\\[Link]',
[Link])

Actually, we sometimes need to this method Blog app


when we should print strings with with
embedded backslashes: Tornado
([Link]
>>> path = r'C:\new\[Link]'
>>> path
'C:\\new\\[Link]'
Multithreadin
>>> print(path) ...
C:\new\[Link] ([Link]
>>> len(path)
15
Python
Network
As we've seen in numeric representation, Programming
the default format at the interactive prompt I - Basic
prints results as they were coded. So, Server /
Client : A
escape backslashes are in the output. The
Basics
print provides a more user-friendly format
([Link]
that shows that there is actually only on
backslash in each spot. Python
Network
Triple Quotes for Programming
I - Basic
Multiline Block Strings Server /
A block string is a string literal format with Client : B
File Transfer
triple-quotes. It is for coding multiline text
([Link]
data.

Python
Network
>>> Python = """Python aims to combine
Programming
"remarkable power
with very clear syntax", and ..."""
II - Chat
>>> Python Server /
'Python aims to combine\n"remarkable p Client
([Link]
Though the string spans three lines, Python
Python
collects all the triple-quoted text into a
Network
single multiline string with embedded
Programming
newline characters (\n) at the places where III - Echo
our code has line breaks. Server using
socketserver
If we print it instead of echoing: network
framework
([Link]
>>> print(Python)
Python aims to combine Python
"remarkable power Network
with very clear syntax", and ... Programming
>>>
IV -
Asynchronou
Request
Handling :
ThreadingMix
Indexing and Slicing and
ForkingMixIn
We can access strong components by ([Link]
position because strings are order
collections of characters. Python
Interview
Questions I
([Link]

Python
Interview
Questions II
([Link]

Python
Interview
Python o sets start at 0 and end at one less Questions
than the length of the string. It also lets us III
fetch items from sequences such as strings ([Link]
using negative o sets. A negative o set is
Python
added to the length of a string to derive a
Interview
positive o set. We can also thing of negative
Questions
o sets as counting backward from the end. IV
([Link]
>>> S = 'Picasso'
Python
>>> # Indexing from front and end
>>> S[0], S[-1], S[-4]
Interview
('P', 'o', 'a') Questions V
([Link]
>>> # Slicing: extract a section
>>> S[1:3], S[2:], S[:-1]
Image
('ic', 'casso', 'Picass')
processing
with Python
The basics of slicing are straightforward. image
When we index a sequence object such as a library
string on a pair of o set separated by a Pillow
colon, Python returns a new object ([Link]
containing the contiguous section. The left
Python and
o set is taken to be the lower bound
C++ with SIP
(inclusive) and the right is the upper bound
([Link]
(noninclusive). In other words, Python
fetches all items from the lower bound up to PyDev with
but not including the upper bound. Then, it Eclipse
returns a new object containing the fetched ([Link]
items. If omitted, the left and right bounds
default to o and the length of the object, Matplotlib
([Link]
respectively.
1. Indexing Redis with
S[i] fetches components at o sets: Python
1. The rst item is at o set 0. ([Link]

2. Negative indexes mean to count


NumPy
backward from the end or right.
array basics
3. S[0] fetches the rst item. A
4. S[-2] fetches the second item from ([Link]
the end (same as S[len(S)-2]).
2. Slicing NumPy
S[i:j] extracts contiguous sections of Matrix and
sequences: Linear
Algebra
1. The upper bound is noninclusive.
([Link]
2. Slice boundaries default to 0 and
the sequence length, if omitted.
Pandas with
3. S[1:3] fetches items at o sets 1 up NumPy and
to but not including 3. Matplotlib
4. S[1:] fetches items at o set 1 ([Link]
through the end (the sequence
length). Celluar
Automata
5. S[:3] fetches items at o set 0 up to
([Link]
but not including 3.

Batch
6. S[:-1]fetches items at o set 0 up to gradient
but not including the last item. descent
7. S[:] fetches items at o sets o algorithm
([Link]
through the end - this e ectively
performs a top-level copy of S.
Longest
Common
The last item is very common trick. It makes Substring
a full top-level copy of a sequence object Algorithm
which is an object with the same value but a ([Link]
distinct piece of memory. This isn't very
Python Unit
useful for immutable objects like strings but
Test - TDD
it is very useful for objects that may be
using
changed in-place such as lists.
[Link]
class
([Link]

Simple tool
- Google
The Third Limit and Slice page
Objects ranking by
Slice expressions have an optional third keywords
([Link]
index as a step or stride:
Google App
X[i:j:k]
Hello World
([Link]
That means "extract all the items in X, from
o set i through j-1 by k." Google App
webapp2
and WSGI
>>> S = 'Edsger Dijkstra' ([Link]
>>> S[1:10:2]
'dgrDj'
Uploading
>>> S[::2]
Google App
'Ese ikta'
Hello World
([Link]
A stride of -1 indicates that the slice should
go from right to left. The net e ect is to Python 2 vs
reverse the sequence: Python 3
([Link]

>>> S[::-1] virtualenv


'artskjiD regsdE'
and
virtualenvwra
With a negative stride, the meanings of the ([Link]
rst two bounds are reversed. In other
words, the slice S[5:1:-1] fetches the items Uploading a
big le to
from 2 to 5, in reverse order:
AWS S3
>>> S = '01234567'
using boto
>>> S[5:1:-1]
'5432'
module
([Link]

Scheduled
stopping
and starting
an AWS
instance
([Link]
more
Cloudera
CDH5 -
Scheduled
stopping

Python tutorial and starting


services
([Link]

Python Home Removing


([Link] Files -
Rackspace
Introduction API with curl
([Link]
and

You might also like