How to use split in python
This article mainly introduces the relevant knowledge of "how to use split in python". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use split in python" can help you solve the problem.
First, function description
1. Split () function
Syntax: str.split (str= "", num=string.count (str)) [n]
Parameter description:
Str: represents as a delimiter, defaults to a space, but cannot be empty (''). If there is no delimiter in the string, the entire string is taken as an element of the list
Num: indicates the number of splits. If there is a parameter num, it is only separated into num+1 substrings, and each substring can be assigned to a new variable
[n]: indicates that the nth slice is selected
Note: when using spaces as delimiters, items that are empty in the middle are automatically ignored
2. Os.path.split () function
Syntax: os.path.split ('PATH')
Parameter description:
PATH refers to the full path of a file as a parameter:
If a directory and file name are given, the output path and file name
If a directory name is given, the output path and empty file name
II. Examples
1. Example 1 shows how to use the split () function.
#! / usr/bin/python#-*-coding: UTF-8-*-str = "Line1-abcdef\ nLine2-abc\ nLine4-abcd"; print str.split (); # is delimited by spaces, including\ nprint str.split (', 1); and # is separated by spaces into two
The output of the above example is as follows:
['Line1-abcdef',' Line2-abc', 'Line4-abcd'] [' Line1-abcdef','\ nLine2-abc\ nLine4-abcd']
2. Example 2, with the # sign as the separator, specify the second parameter as 1, and return two parameter lists.
#! / usr/bin/python#-*-coding: UTF-8-*-txt = "Google#Runoob#Taobao#Facebook" # the second parameter is 1 and returns two parameter lists x = txt.split ("#", 1) print x
The output of the above example is as follows:
['Google',' Runoob#Taobao#Facebook'] this is the end of the introduction to "how to use split in python". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.