Tanggal :September 22, 2020

py37. split in Python

Spread the love

We have an input tuple of strings with two values separated by ‘:’. The value on the left is a string, whereas the value on the right is an integer.

We want to get a list of strings for the value that go before ‘:’.

We want to get an list of integers for the values that go after ‘:’.

We use list comprehensions to get the lists.

In addition, we create a combined list, with the values extracted from the input sequence, returned as a list of 2-length tuples. The split method of a string object is used. Notice we have to write the string, then a period to get any method or attributes. This leads to better management of the global namespace. For the split method we give the string to split as well as the split character.

# ex37.py
from __future__ import print_function
chr_vec = "time:30","pos:45","loc:5"
first_vec = [c.split(":")[0] for c in chr_vec]
second_vec = [int(c.split(":")[1]) for c in chr_vec]
combined_vec = [(c.split(":")[0],
int(c.split(":")[1])) for c in chr_vec]
print("original: ", chr_vec)
print("first_vec = ", first_vec)
print("second_vec = ", second_vec)
print("combined_vec = ", combined_vec)
#original: ('time:30', 'pos:45', 'loc:5')
#first_vec = ['time', 'pos', 'loc']
#second_vec = [30, 45, 5]
#combined_vec = [('time', 30), ('pos', 45), ('loc', 5)]

Leave a Reply

Your email address will not be published. Required fields are marked *