0% found this document useful (0 votes)
6 views38 pages

Python String Data Types and Methods

Uploaded by

d.q.huy791
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)
6 views38 pages

Python String Data Types and Methods

Uploaded by

d.q.huy791
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

4/7/2023

String data type for


Application Programming with Python

1
4/7/2023

Methods – on strings and other things

 Strings, revisited
 Objects and their methods
 Indexing and slicing
 Some commonly used string methods

 A string is a sequence of zero or more characters


 A string is delimited (begins and ends) by single or double quotes

 poem = 'Ode to a Nightingale'


 lyric = "Roll on, Columbia, roll on"
 exclamation = "That makes me !#? "
 The empty string has zero characters ('' or "")

2
4/7/2023

Quote characters in strings


 You can include a single quote in a double quoted string or a double quote in a single
quoted string
will = "All the world's a stage"
ben = 'BF: "A penny saved is a penny earned"'
 To put a single quote in a single quoted string, precede it with the backslash ('\') or
'escape' character.
>>> will = 'All the world\'s a stage'
>>> print(will)
All the world's a stage
 The same goes for double quotes
>>> ben = "BF: \"A penny saved is a penny earned\""
>>> print(ben)
BF: "A penny saved is a penny earned"

Putting a format character in a string


 A format character is interpreted by the print() function to change the layout of text
 To put a format character in a string, precede it with the backslash ('\')
 A newline is represented by '\n'
>>> juliette = 'Good night, good night\nParting is such sweet sorrow'
>>> print(juliette)
Good night, good night
Parting is such sweet sorrow
 A tab is represented by '\t'
>>> tabs = 'col0\tcol1\tcol2'
>>> print(tabs)
col0 col1 col2

3
4/7/2023

Index of string characters


 The first character of a string has index 0
>>> greeting = 'hello, world'
>>> greeting[0]
'h'
>>> 'hello, world'[0]
'h'
 You can also count back from the end of a string, beginning with -1
>>> greeting = 'hello, world'
>>> greeting[-1]
'd'
>>> 'hello, world'[-1]
'd'
7

Slicing a string
 You can use indexes to slice (extract a piece of) a string
 aStr[i:j] is the substring that begins with index i and ends with (but does not include) index j
 >>> greeting = 'hello, world'
>>> greeting[1:3]
'el'
>>> greeting[-3:-1]
'rl'
 omit begin or end to mean 'as far as you can go'
>>> print(greeting[:4], greeting[7:])
hell world
 aStr[i:j:k] is the same, but takes only every k-th character
>>> greeting[Link]
'l,wr'

4
4/7/2023

Index/slice a string vs index/slice a list


How they're the same and how they're different

 You can index a list or string by providing an integer index


value, beginning with 0 from the left or -1 from the right [i].
 You can slice a list or string by providing begin and end
values ([i:j]) or begin, end and step values ([i:j:k])
 You can omit begin or end ([:j] or [i:]) to mean 'as far as you
can go’

List index vs string index (continued)


DIFFERENT:
 if you reference a single element of a list with the index operator ([i]), its type is the
type of that element
>>> abc = ['a', 'b', 'c']
>>> abc[0]
'a'
>>> type(abc[0])
<class 'str'>
 If you slice (extract a piece of) a list with begin and end ([i:j]) values, you get a sublist
(type list)
>>> abc[0:2]
['a', 'b']
>>> type(abc[0:2])
<class 'list'>

10

5
4/7/2023

String methods
 A method is a function that is bundled together with a particular type of object
 A string method is a function that works on a string
 This is the syntax of a method:
[Link](parameterList)
 For example,
>>> 'avocado'.index('a')
0
returns the index of the first 'a' in 'avocado'
 You can also use a variable of type string
>>> fruit = 'avocado'
>>> [Link]('a')
0

11

Method parameters

 Like any function, a method has zero or more parameters


 Even if the parameter list is empty, the method still works on the 'calling'
object:
>>> 's'.isupper()
False
 Here is a string method that takes two parameters:
>>> aStr = 'my cat is catatonic'
>>> [Link]('cat', 'dog')
'my dog is dogatonic'

12

6
4/7/2023

Strings are immutable


 A string is immutable -- once created it can not be modified
 When a string method returns a string, it is a different object; the original string is not
changed
>>> aStr = 'my cat is catatonic'
>>> newStr = [Link]('cat', 'dog')
>>> newStr
'my dog is dogatonic'
>>> aStr
'my cat is catatonic'
 However, you can associate the old string name with the new object
>>> aStr = 'my cat is catatonic'
>>> aStr = [Link]('cat', 'dog')
>>> aStr
'my dog is dogatonic'

13

Python string methods


 Python has many very useful string methods
 You should always look for and use an existing string method before coding it again for
yourself. Here are some
[Link]()
[Link]() # s=‘yen tinh’; [Link](‘n’)=> count the number of ‘n’
[Link](‘item’) / [Link](‘item’) # check if the string start with
[Link]() / [Link]()
[Link]()
[Link]()/[Link]()/[Link]()/[Link]() [Link]()
[Link]() / [Link]()
[Link]()
[Link]()
[Link]()

14

7
4/7/2023

txt = "Hello, welcome to my world."

x = [Link]("welcome")

print(x)

txt = "For only {price:.2f} dollars!"


print([Link](price = 49))

2/28/17

15

txt = "Company12"
x = [Link]()
print(x)

2/28/17

16

8
4/7/2023

The split method


 The string method split() lets us separate a string into useful parts
Common use: splitting a sentence into its words
 Splits by space characters by default, but you can give it a different
'separator' string
>>> s = "Captain, incoming transmission!"
>>> print([Link](‘ ’))
['Captain,', 'incoming', 'transmission!']
>>> s = "a one, a two, a one two three four"
>>> print([Link](', '))
['a one', 'a two', 'a one two three four']

17

The strip method


 The string method strip() “cleans” the edges of a string by removing the
character(s) you specify (default: spaces)
>>> s = "(hello!)"
>>> print([Link]("()!"))
hello

 The string module contains a useful variable for this, called punctuation
(like how the math module has pi)
>>> import string
>>> [Link]
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

18

9
4/7/2023

Using split() and strip() together


 The split method is useful for extracting words, and the strip method is
useful for cleaning them up
 Remember that strip() is a string method, not a list method
>>> import string
>>> words = ['How', 'are', 'you,', 'sir?']
>>> print([Link]([Link]))
AttributeError: 'list' object has no attribute 'strip'

 So, how can we clean up every word in a sentence, once we've split it?

19

Using split() and strip() together


 The strip() method works on one “word” at a time
 So, take it one word at a time
>>> import string
>>> words = ["It's", 'warm', 'today', 'yeah?']
>>> for item in words:
print([Link]([Link]))
It's
warm
today
yeah
Side question: why can't we just use the replace() method to get rid of punctuation like
this?

20

10
4/7/2023

2/28/17

21

Python string method documentation

 You can find the meaning of each of these string methods in the Python
documentation
 Some operations on strings also work with other sequence types, both mutable
and immutable. For example:
x in s
x not in s
s+t
s*n / n*s
len(s)
min(s)
max(s)

22

11
4/7/2023

Strings and the print() function


 The print() function always prints a string. The input() function always inputs a
string.
 Every object in Python has a string representation. Therefore, every object can
be printed.
 When you print a number, a list or a function it is the string representation of
the object that is printed
 print() takes 0 or more arguments and prints their string representations,
separated by spaces
>>> print('pi =', 3.14)
pi = 3.14
>>> def f():
pass
>>> print(f)
<function f at 0x02C4BD20>

23

The print separator and end


 By default, print() separates multiple outputs with spaces
 You can change this to any string that you want, for example, a colon and a space (': ')
>>> print(1, 2, 3, sep=': ‘) # sep is short for seperate
1: 2: 3
 By default, print() ends its output with a newline ('\n')
>>> for i in range(3):
print(i)
0
1
2
 You can change this, for example, to a hyphen
>>>for i in range(3):
print(i, end='-')
0-1-2-

24

12
4/7/2023

The string format method

 The string format() method allows you detailed control over what is
printed and its arrangement (including alignment; width; your choice of
date, time and number formats; and many other things).
 Here is an example of how [Link]() can be used to control what is
printed:
>>> print('{} is {}'.format('Big Bird', 'yellow'))
Big Bird is yellow
>>> print('{} is {}'.format('Oscar', 'grumpy'))
Oscar is grumpy

25

2/28/17

26

13
4/7/2023

2/28/17

27

28

14
4/7/2023

29

2/28/17

30

15
4/7/2023

2/28/17

31

ljust(): Returns a left justified version of the string

2/28/17

32

16
4/7/2023

title() : Make the first letter in each word upper case:

2/28/17

33

capitalize(): Converts the first character to upper case

txt = "hello, and welcome to my world."


x = [Link]()
print (x)

Hello, and welcome to my world.

34

34

17
4/7/2023

Python String casefold() Method: Converts string into lower case

txt = "Hello, And Welcome To My World!"


x = [Link]()
print(x)

hello, and welcome to my world!

35

35

center(): Returns a centered string

txt = "banana”
x = [Link](20)
print(x)
Print the word "banana", taking
up the space of 20 characters,
with "banana" in the middle:

36

36

18
4/7/2023

count(): Returns the number of times a specified value occurs in a string

txt = "I love apples, apple are my favorite fruit"


x = [Link]("apple")
print(x)

Return the number of times the value "apple" appears


in the string

37

37

encode(): Returns an encoded version of the string

UTF-8 encode the string:


txt = "My name is Ståle"

x = [Link]()

print(x)

b'My name is St\xc3\xe5le'

38

38

19
4/7/2023

endswith(), Returns true if the string ends with the specified value

Check if the string ends with a punctuation sign (.):

txt = "Hello, welcome to my world.“


x = [Link](".")
print(x)

39

39

expandtabs(): Sets the tab size of the string

expandtabs():
txt = "H\te\tl\tl\to"

x = [Link](2)

print(x) Sets the tab size of the string

40

40

20
4/7/2023

Python String find() Method

Searches the string for a specified value and returns


the position of where it was found.

txt = "Hello, welcome to my world."


x = [Link]("welcome")
print(x)

41

41

Python String format() Method

Insert the price inside the placeholder, the price should


be in fixed point, two-decimal format:
txt = "For only {price:.2f} dollars!"
print([Link](price = 49))

For only 49.00 dollars!

42

42

21
4/7/2023

Python String index() Method

Where in the text is the word "welcome"?:

txt = "Hello, welcome to my world."

x = [Link]("welcome")

print(x)

43

43

Python String isalnum() Method

Check if all the characters in the text are alphanumeric:


txt = "Company12"

x = [Link]()

print(x)

Returns True if all characters in the string are alphanumeric

44

44

22
4/7/2023

Python String isalpha() Method

txt = "CompanyX"

x = [Link]()

print(x)

The isalpha() method returns True if all the characters are alphabet letters (a-z)

45

45

Python String isascii() Method

Check if all the characters in the text are ascii characters:


txt = "Company123"
x = [Link]()
print(x)

4/7/2023

46

23
4/7/2023

Python String isdigit() Method

Check if all the characters in the text are digits:

txt = “210109800"

x = [Link]()

print(x)

4/7/2023

47

Python String isidentifier() Method

Check if the string is a valid identifier:


txt = "Demo"

x = [Link]()

print(x)

Returns True if the string is an identifier

4/7/2023

48

24
4/7/2023

Python String islower() Method

Check if all the characters in the text are in lower


case:

txt = "hello world!"


x = [Link]()
print(x)

Returns True if all characters in the string are lower case

4/7/2023

49

Python String isnumeric() Method

Check if all the characters in the text are numeric:


txt = "565543"

x = [Link]()

print(x)
---------------------------------------------------
Returns True if all characters in the string are alphanumeric

4/7/2023

50

25
4/7/2023

Python String isprintable() Method

Check if all the characters in the text are printable:


txt = "Hello! Are you #1?"
x = [Link]()
print(x)

Returns True if all characters in the string are printable

4/7/2023

51

Python String isspace() Method

Check if all the characters in the text are whitespaces:


txt = " "
x = [Link]()
print(x)
Returns True if all characters in the string are whitespaces

4/7/2023

52

26
4/7/2023

Python String istitle() Method

Check if each word start with an upper case letter:


txt = "Hello, And Welcome To My World!"
x = [Link]()
print(x)
Returns True if the string follows the rules of a title

4/7/2023

53

Python String isupper() Method

Check if all the characters in the text are in upper case:


txt = "THIS IS NOW!"

x = [Link]()

print(x)

Returns True if all characters in the string are upper case

4/7/2023

54

27
4/7/2023

Python String join() Method

Join all items in a tuple into a string, using a hash


character as separator:
myTuple = ("John", "Peter", "Vicky")

x = "#".join(myTuple)

print(x)

4/7/2023

55

Python String ljust() Method

Return a 20 characters long, left justified version of the


word "banana":
txt = "banana"
x = [Link](20)
print(x, "is my favorite fruit.")

4/7/2023

56

28
4/7/2023

Python String lower() Method

Lower case the string:


txt = "Hello my FRIENDS"

x = [Link]()

print(x)

4/7/2023

57

Python String lstrip() Method

Remove spaces to the left of the string:


txt = " banana “
x = [Link]()
print("of all fruits", x, "is my favorite")

4/7/2023

58

29
4/7/2023

Python String maketrans() Method

Create a mapping table, and use it in the translate()


method to replace any "S" characters with a "P"
character:
txt = "Hello Sam!"
mytable = [Link]("S", "P")
print([Link](mytable))

4/7/2023

59

Python String partition() Method

Search for the word "bananas", and return a tuple with


three elements:
1 - everything before the "match"
2 - the "match"
3 - everything after the "match"

txt = "I could eat bananas all day"


x = [Link]("bananas")
print(x)

4/7/2023

60

30
4/7/2023

Python String replace() Method

Replace the word "bananas":


txt = "I like bananas"

x = [Link]("bananas", "apples")

print(x)

4/7/2023

61

Python String rfind() Method

Where in the text is the last occurrence of the string


"casa"?:
txt = "Mi casa, su casa."
x = [Link]("casa")
print(x)

4/7/2023

62

31
4/7/2023

Python String rindex() Method

Searches the string for a specified value and returns


the last position of where it was found.
EX: Where in the text is the last occurrence of the
string "casa"?:
txt = "Mi casa, su casa."
x = [Link]("casa")
print(x)

4/7/2023

63

Python String rjust() Method

Returns a right justified version of the string


Ex: Return a 20 characters long, right justified version
of the word "banana":
txt = "banana"
x = [Link](20)
print(x, "is my favorite fruit.")

4/7/2023

64

32
4/7/2023

Python String rpartition() Method

Returns a tuple where the string is parted into three parts.


Ex: Search for the last occurrence of the word "bananas", and return a
tuple with three elements:
1 - everything before the "match"
2 - the "match"
3 - everything after the "match"
txt = "I could eat bananas all day, bananas are my favorite fruit"
x = [Link]("bananas")
print(x)

4/7/2023

65

Python String rsplit() Method

Splits the string at the specified separator, and returns


a list.
Ex: Split a string into a list, using comma, followed by a
space (, ) as the separator:
txt = "apple, banana, cherry"
x = [Link](", ")
print(x)

4/7/2023

66

33
4/7/2023

Python String rstrip() Method

Splits the string at the specified separator, and returns


a list
Ex: Remove any white spaces at the end of the string:
txt = " banana "
x = [Link]()
print("of all fruits", x, "is my favorite")

4/7/2023

67

Python String splitlines() Method

Splits the string at line breaks and returns a list.


EX: Split a string into a list where each line is a list
item:
txt = "Thank you for the music\nWelcome to the jungle"
x = [Link]()
print(x)

4/7/2023

68

34
4/7/2023

Python String startswith() Method


Returns true if the string starts with the specified value
Ex: check if the string starts with "Hello":
txt = "Hello, welcome to my world."
x = [Link]("Hello")
print(x)
Returns true if the string starts with the specified value

4/7/2023

69

Python String strip() Method


Returns a trimmed version of the string
Ex: Remove spaces at the beginning and at the end of
the string:
txt = " banana "
x = [Link]()
print("of all fruits", x, "is my favorite")

4/7/2023

70

35
4/7/2023

Python String swapcase() Method

Swaps cases, lower case becomes upper case and vice


versa
Ex: Make the lower case letters upper case and the
upper case letters lower case:
txt = "Hello My Name Is PETER"
x = [Link]()
print(x)
Swaps cases, lower case becomes upper case and vice versa

4/7/2023

71

Python String title() Method

Converts the first character of each word to upper case.


Ex: Make the first letter in each word upper case:
txt = "Welcome to my world"
x = [Link]()
print(x)

4/7/2023

72

36
4/7/2023

Python String translate() Method

Returns a translated string.


Replace any "S" characters with a "P" character:
#use a dictionary with ascii codes to replace 83
(S) with 80 (P):
mydict = {83: 80}
txt = "Hello Sam!"
print([Link](mydict))

4/7/2023

73

4/7/2023

74

37
4/7/2023

Python String upper() Method

Converts a string into upper case.


Ex: Upper case the string:
txt = "Hello my friends"
x = [Link]()
print(x)

4/7/2023

75

Python String zfill() Method

Fills the string with a specified number of 0 values at


the beginning
Ex: Fill the string with zeros until it is 10 characters
long:
txt = "50”
x = [Link](10)
print(x)

4/7/2023

76

38

You might also like