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 to use Python string function

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article is about how to use the Python string function. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The friendliness of Python is that it provides a very good and powerful function module, as well as many simple and convenient string functions for the use of strings. Python string comes with a lot of useful functions, before the string function to introduce a very useful dir () built-in function, because for every beginner or master level python programmer, can not fully remember all the methods. This function can view all of these functions, call dir and specify parameters as any string, such as dir (""), whose return values include variables, methods, and defined types that can be used by the string.

> dir (") ['_ _ add__','_ _ class__','_ _ contains__','_ _ delattr__','_ _ dir__','_ _ doc__','_ _ eq__','_ _ format__','_ _ ge__','_ getattribute__','_ getitem__','_ getnewargs__','_ _ gt__','_ _ hash__' '_ _ init__',' _ _ init_subclass__','_ _ iter__','_ _ le__','_ _ len__','_ _ lt__','_ _ mod__','_ _ mul__','_ _ ne__','_ _ new__','_ reduce__','_ reduce_ex__','_ repr__','_ _ rmod__' '_ rmul__',' _ setattr__','_ sizeof__','_ str__','_ subclasshook__', 'capitalize',' casefold', 'center',' count', 'encode',' endswith', 'expandtabs',' find', 'format',' format_map', 'index',' isalnum', 'isalpha',' isdecimal', 'isdigit',' isidentifier', 'islower' 'isnumeric', 'isprintable',' isspace', 'istitle',' isupper', 'join',' ljust', 'lower',' lstrip', 'maketrans',' partition', 'replace',' rfind', 'rindex',' rjust', 'rpartition',' rsplit', 'rstrip',' split', 'splitlines',' startswith', 'strip',' swapcase', 'title',' translate', 'upper' 'zfill']

It also provides queries for functional functions, such as the frequently used math () function, so whether it is a string function or other functions described later, we can use the built-in dir () function to understand the types, definitions, and so on of other functions. The string functions described below are described separately according to their different functions. the implementation function of the function roughly includes the following six functions: indexing special strings, formatting characters, modifying string case, viewing string-specific formats, replacing specific strings, and splitting specific strings.

1 search string function

If we need to find a specific substring in a string, the following functions are usually involved:

Although these functions implement the ability to search for specific strings, there are some differences:

1. The difference between the functions index and find is that the specified substring is not found. The example is as follows:

The function index throws an exception ValueError, and if the specified substring is not found, the function find returns-1.

two。 String search functions usually search from left to right (from beginning to end), but functions that start with r search from right to left. For example:

As you can see, the functions find and index return the index of the starting position of the first occurrence of the incoming string, while rfind and rindex return the index of the starting position of the last occurrence of the incoming string.

2 set string format function

The following table lists some functions that format strings:

The center (), ljust () and rjust () functions are rarely used in daily use, but format () after Python2.6 is widely used by string processors. To use the format function, you need to provide it with a variable or value. A simple example: {0} and {1} in a string refer to the parameters of format: they will be replaced with the value of the corresponding string or variable. You can also use the name of the keyword parameter

>'{0} like eat {1} '.format (' Wangzi','banana') 'Wangzi like eat banana' >' {who} {id} is Linda'.format (who='My',id='name')'My name is Linda'

These are some relatively simple examples, and more details can be found in string-Common string operations-Python 3.10.1 documentation. Here is an actual use case for grabbing jmx values. In the process of using big data component, we usually grab the data of the jmx API to obtain details, and then transfer the data to the relevant display system to monitor and display: for example, we need to grab a queue task id, user, run time and other indicators (here IP has been processed, you can consult the blogger if you have any questions).

Import jsonimport urllib3import re def get_ative_resourcemanager (rm1, rm2): http = urllib3.PoolManager () rm_list = [rm1, rm2] for resourcemanager in rm_list: url = 'http://{0}/ws/v1/cluster/info'.format(resourcemanager) response = http.request (' GET' Url) data = json.loads (response.data) ha_state = data ['clusterInfo'] [' haState'] if ha_state = = "ACTIVE": return resourcemanager'''Conversion time function'''# is converted to hour/minutesdef conver_time (allTime) in milliseconds: hours = (allTime/ (60,60,1000) return hours''get active resourcemanager yarn application metrics'''def get_queue_metrics (): active_resoucemanager = get_ative_resourcemanager ('ip1:port' 'ip2:port') http = urllib3.PoolManager () url =' http://{0}/ws/v1/cluster/apps'.format(active_resoucemanager) response = http.request ('GET' Url) data = json.loads (response.data). Get ('apps'). Get (' app') length = len (data) for i in range (length):''determine application status' 'application_state = data [I] [' state'] queue = data [I] ['queue'] queue_name = re.findall Re.IGNORECASE) # print (mobdi_queue) if (application_state = = 'RUNNING' or application_state = =' ACCEPTED'): if queue_name: id_metric = data [I] ['id'] user_metric = data [I] [' user'] queue_metrics = data [I] ['queue'] Elapsed_time = data [I] ['elapsedTime'] runtime_metric = conver_time (elapsed_time) print (str (id_metric) + "+ str (user_metric) +" + str (queue_metrics) + "" + str (runtime_metric)) if _ name__ = =' _ main__': 'get_queue_metrics ()

Execution result:

3 change the case function of the string

There are five functions that provide a function for changing the case of a string:

Python provides various functions to modify the case of letters, such as the table above. Note, however, that Python does not modify the string, but creates and returns a new string in these functions, without actually modifying the string source string.

4 selected string function

The selected string function is usually used to delete extra strings at the beginning or end of a string, including the striip,lstrip and rstrip functions.

1. If you do not add a string, the blank string is deleted:

two。 Delete string case:

5 split string function

Python provides the following functions for splitting a string, mainly splitting a string into multiple substrings.

Note that there are two strings, string and string1, in the example. The functions partition and rpartition split the string into three parts. These two functions always return a value that consists of three strings in the form (head, sep, tail). The function split, with the specified string as the delimiter, divides the string into a series of substrings and returns a list of strings, which always begins and ends with [and], respectively, and separates elements with commas. The splitlines function, separated by lines ('\ r\ nlines,\ n'), returns a list of lines as elements, rarely used, and determines for itself whether the string contains newline characters.

6 replace string function

Python has two built-in string replacement functions, including:

Thank you for reading! This is the end of the article on "how to use the Python string function". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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