Python learns how to splice list items
- 2020-06-01 10:13:22
This article is about the implementation of Python list item splicing 1 tips, to share the reference for everyone to learn, let's take a look at the detailed introduction:
data_list = ['a', 'b', 'c', 'd', 'e', 'f'] separator = '\t' data_joined = separator.join(data_list) print(data_joined)
Its output is:
a b c d e f
When implementing many business requirements, each item in the list needs to be concatenated into a string according to some kind of delimiter to complete some serialization mode for network transmission or logging, or to form some kind of intermediate value for subsequent processes.
Why is it a trick?
Work process, the application of similar scenes, almost done through for cycle related needs is the first think of, but adopt for circulation, will more than a few lines of code to spend 1 more time to understand the logic of the code, especially involves the need to deal with the last list item 1 case: we don't want to end up with a string of suffix is a delimiter.
1. The code is more compact, reducing logic loops and making it easier to read
2. Built-in method, which is more efficient than stitching the string yourself
1. In fact, this method can also be applied to tuple type, collection type, or even a generator type, etc., not only to list type;
2. Each item in the iterable type is required to be of string type;
3. In Java 8, the String class also provides a similar static method join, and Java programming can use more compact code to concatenate strings;