COMP101 Introduction to Programming 2020-21 Lecture-24 List Manipulation

[Pages:16]COMP101 Introduction to Programming

2020-21

Lecture-24 List Manipulation

1

1

Python: List join() method

? Convert list to a string ? Use the `join()' method ? Syntax:

separator_string.join(list_name)

? separator_string can be any character to separate the words in the string

2

Python: List join

word_list = ["name one", "name two"] print (word_list) ['name one', 'name two']

word_list_string = " ".join(word_list)

print (word_list_string)

name one name two

name one and name two are separated by a space because we specified a space in the separator_string: word_list_string = " " ...

3

Python: List join

word_list = ["name one", "name two"] print (word_list) ['name one', 'name two']

word_list_string = ",".join(word_list)

print (word_list_string)

name one, name two

name one and name two are separated by a comma because we specified a comma in the separator_string: word_list_string = "," ...

4

Python: List join

word_list = ["This", "is", "a", "sentence"] word_list_string = " ".join(word_list) print (word_list_string) This is a sentence

The separator_string here is a space " " ? there is a space between the quotes If we don't physically put a space in it: word_list_string = "".join(word_list) the words (elements) in the list all join up: Thisisasentence

5

Python: List join

word_list = ["This", "is", "a", "sentence"] word_list_string = "*** ".join(word_list) print (word_list_string) This*** is*** a*** sentence

separator_string can be any character

6

Python: List join

word_list = ["This", "is", "a", "sentence"] word_list_string = "\t".join(word_list) print (word_list_string) This is a sentence

Separator puts a tab between each element

7

Python: String split() method

? Convert a string to a list ? split() ? the `split string function'

? is a `string method' to split a given string into a list

string.split(separator)

? The separator defaults to whitespace, or can be user-specified

8

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download