0% found this document useful (0 votes)
4 views17 pages

Lu 05

Uploaded by

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

Lu 05

Uploaded by

Spectre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 17

CHAPTER 5

Text Strings
Strings
Strings Are a sequence of Characters for example: I am a string

But what type of Characters? It’s smallest nit in writing system,, includes letter, digits, symbols,
punctuation, and even white spaces

Character is defined by its meaning(how its used), not how it looks


Creating strings

Two methods on creating string:


• Single or double quotes
• Use str()
Creating with Quotes
>>> ‘Snap’
‘Snap
>>> “Crackle”
‘Crackle’
>>> "'Nay!' said the naysayer. 'Neigh?' said the
horse.“
Why is there two kinds of "'Nay!' said the naysayer. 'Neigh?' said the horse.“
quotes characters? >>> 'The rare double quote in captivity: ".’
• The purpose is to create 'The rare double quote in captivity: ".’
strings containing quote >>> 'A "two by four" is actually 1 1⁄2" × 3 1⁄2".
''A "two by four" is actually 1 1⁄2" × 3 1⁄2".’
>>> "'There's the man that shot my paw!' cried the
limping hound.“
"'There's the man that shot my paw!' cried the
limping hound."
Create with str()
Python use str() function internally when you call print()
>>> str(98.6)
with object
'98.6’
>>> str(1.0e4)
'10000.0’
>>> str(True)
'True'
Escape with \
Allow you to escape meaning of some
characters within the string
>>> palindrome = 'A man,\nA plan,\nA canal:\
nPanama.’
>>> print(palindrome)
A man,
A plan, Can use \t (tab) to align text
A canal:
>>> print('\tabc’)
Panama
abc
>>> print('a\tbc’)
a bc
>>> print('ab\tc’)
ab c
>>> print('abc\t’)
abc
Combing and duplicating strings
Combine by Using + Duplicate with*
Can combine string literal or variables with the + Can use * operator to duplicate strings:
operator:
(try to type these line into your interpreter)
>>> 'Release the kraken! ' + 'No, wait!’
'Release the kraken! No, wait!’ >>> start = 'Na ' * 4 + '\n’
>>> middle = 'Hey ' * 3 + '\n’
>>> "My word! " "A gentleman caller!“
'My word! A gentleman caller! >>> end = 'Goodbye.’
'>>> "Alas! ""The kraken!“ >>> print(start + start + middle + end
'Alas! The kraken!

Notice that * has higher precedence than +


Get a Character with []
To get single Char from string.
Specify offset inside square brackets after
string name. (Note leftmost offset is 0
next is 1)
>>> letters = 'abcdefghijklmnopqrstuvwxyz’
>>> letters[0]
'a’
>>> letters[1]
'b’
>>> letters[-1]
‘z
'>>> letters[-2]
‘y
'>>> letters[25]’
z
'>>> letters[5]
'f
Manipulating strings
Get a substring with a slice Get Length with len():
• [ : ] extracts entire sequence start to end
• [ start : ] specifies from start offset to end will count the
• [: end ] specifies form beginning to end offset minus 1 characters in a string
• [ start : end] indicates from start offset to end offset minus 1
• [start : end : step] extracts from start offset and end offset minus 1, skipping
characters by step

Split with split()


• Unlike len(), functions are specific to strings
• To use string function, type name of the sting, a dot, the
name of the function and any argument:
• String.function(arguments)(discus functions in chapter 9)
• Can use the built-in string split() function to break a string
into a list
>>> tasks = 'get gloves,get mask,give cat vitamins,call
ambulance’
>>> tasks.split(',’)
['get gloves', 'get mask', 'give cat vitamins', 'call ambulance']
Manipulate strings continued
Combine by Using join()
• Join() function opposite of split()
• Collapse a list of string into a Single string

>>> crypto_list = ['Yeti', 'Bigfoot', 'Loch Ness Monster’]


>>> crypto_string = ', '.join(crypto_list)
>>> print('Found and signing book deals:', crypto_string
)Found and signing book deals: Yeti, Bigfoot, Loch Ness Monster
Substitute by Using replace()
• Replace() 0 simple substring
substitution
• Give old substring a new one

>>> setup = "a duck goes into a


bar...“
>>> setup.replace('duck', 'marmoset’)
'a marmoset goes into a bar...’
>>> setup'a duck goes into a bar...
Strip with strip()
• Common to strip leading or trailing “padding” characters from string, especially
spaces
• Strip() assume that you want to get rid of whitespace characters(‘ ‘, ’\t’ ,’\n’)
• If no arguments is given both ends will strip
• lstrip() strips from left and rstrip() strips from right

>>> world = " earth “


>>> world.strip()
'earth’
>>> world.strip(' ‘)
'earth’
>>> world.lstrip()’
earth ‘
>>> world.rstrip()
' earth'
Case

Well look at some more uses of built-in string function

Function Description
strip() Remove a character from string
capitalize() Capitalize first letter
title() Capitalize all word
upper() Converts all characters to uppercase
lower() Converts all characters to lowercase
swapcase() Swaps uppercase and lowercase
Alignment
Work with some layout function
Strings is aligned within the specified number of spaces

center() Center the string


ljust() Left justify
rjust() Right justify
Formatting

Each python version had its own way of formatting string:


• Old style(supported in Python 2 and 3)
• New style(Python 2.6 and up)
• F-string (Python 3.6 and up)
Old style %

%s String
%d Decimal integer
%x Hex integer
%o Octal integer
%f Decimal float
%e Exponential float
%g Decimal or exponential float
%% A literal %
New style:{} and format()

“New style” format has the form fromat_string.format(data)

>>> thing = 'woodchuck’


>>> '{}'.format(thing)
'woodchuck’

Argument to the format() function need to be in the order as the {} placeholder

>>> thing = 'woodchuck’


>>> place = 'lake’
>>> 'The {} is in the {}.'.format(thing, place)
'The woodchuck is in the lake.' Can specify the argument by position

>>> 'The {1} is in the {0}.'.format(place, thing)


'The woodchuck is in the lake.'
Newest style: f-string
F-string are now the recommended way of formatting string
To make a f-string:
type letter f or F in initial quote
include variable name or expressions within {} to get their values

>>> thing = 'wereduck’


>>> place = 'werepond’
>>> f'The {thing} is in the {place}’
'The wereduck is in the werepond'

You might also like