Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Python split strings like awk?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how Python divides strings like awk". The explanation in the article is simple and clear and easy to learn and understand. Please follow the editor's train of thought to study and learn "how Python divides strings like awk".

[root@localhost ~] # cat demo.txt hello world [root@localhost ~] # [root@localhost ~] # awk'{print$1,$2} 'demo.txt hello world

But what about switching to Python? This could be the result.

> msg='hello world' > msg.split ('') ['hello',' world']

It does not match the result I expected, and multiple spaces will be divided multiple times.

Is there any way to achieve the same effect as awk?

There are two ways.

The first method

Without parameters, this only applies to the treatment of multiple spaces as a single space, which is not applicable if the space is not used as a separator.

> msg='hello world' > msg.split () ['hello',' world']

The second method

Use filter to assist, which applies to all delimiters. Here is an example of the-delimiter.

> msg='hello----world' > msg.split ('-') ['hello',' world'] > filter (None, msg.split ('-')) ['hello',' world']

Isn't it amazing that the first parameter in the impression of filter is a function, and it is amazing to pass None directly here.

After looking at the comments, it turns out that this function will adapt to the case of None. When the first parameter is None, it is very convenient to return a non-null value in the second parameter (iterable object).

Change the way you write a function, you can do this.

> msg='hello----world' > msg.split ('-') ['hello',' world'] > filter (lambda item: True if item else False, msg.split ('-')) ['hello',' world'] Thank you for your reading. That's how Python splits strings like awk. After studying this article, I believe you have a deeper understanding of how Python splits strings like awk, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report