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 strings in Python

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

Share

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

This article introduces the knowledge of "how to use strings in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Definition of string

Python definition characters, strings are not as strict as java, whether single quotation marks, double quotation marks, or even three single quotation marks and double quotation marks can be used to define characters (strings), as long as they appear in pairs. For example:

# single character astata'# use single quotation marks to define the string name='Uranus' # use double quotation marks to define the string code = "Hello World..." # now that we talk about string, how can we not click on the open source code? Class str (object): "" str (object='')-> str str (bytes_or_buffer [, encoding [, errors]])-> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__ () (if defined) or repr (object). Encoding defaults to sys.getdefaultencoding (). Errors defaults to 'strict'. "

Although these are not the main points, it is simple to mention that three single or double quotes are mainly used as document comments, please do not use them to define strings (although there will be no syntax errors).

Today, we will mainly talk about how to define the string of segments. PEP8 stipulates that the length of a line of code should not exceed 120 characters. So what should I do if this happens?

# deprecated usage: line = "Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. "or line =" Create a new string object from the given object. "\" If encoding or errors is specified, "\" then the object must expose a data buffer that will be "\" decoded using the given encoding and error handler. "# better implementation: line = (" Create a new string object from the given object. " The use of .is () in the string "If encoding or errors is specified,"then the object must expose a data buffer that will be"decoded using the given encoding and error handler.")

.is * (), since it is is, it returns only two kinds of results, True or False

Let's first compare the numbers:

Isdigit () True: Unicode digits, byte digits (single byte), full width digits (double bytes), Roman numerals False: Chinese numerals Error: no isdecimal () True: Unicode digits, full width digits (double bytes) False: Roman numerals, Chinese numerals Error: byte digits (single byte) isnumeric () True: Unicode digits, full width digits (double bytes), Roman numerals False: no Error: byte digits (single byte)

Summarize several partial knowledge points:

False '①②③④⑤' isdigit (), isnumeric () is True isdecimal (), and isnumeric () is True!

Let's take a look at another equation:

Isalnum () = isdigit () + isalpha () + isspace () isdigit () means all numbers in the string isalpha () means all characters in the string isspace () indicate that there are one or more spaces in the string to form isalnum () that all numbers and characters in the string are numbers and characters such as numbers and characters such as numbers (a.isdigit ()) # True print (b.isalpha ()) # True print (c.isalnum ()) # True

Methods for string case:

The .isupper () string is all uppercase. The islower () string is all lowercase. Istitle () string is named for the hump in the form of eg: "Hello World"

When is is removed from the above usage, it becomes the corresponding string forwarding method. Learn one set and learn two sets. Buy one get one free. .

Finally, I say one without it. Is*-isinstance (obj,type).

Determine what type of object is. Type optional type is: int,float,bool,complex,str,bytes,unicode,list,dict,set,tuple and type can be an original group: isinstance (obj, (str, int))

Judge the contents of a string

. * with () starts ends not only supports matching between the beginning and the end, but also supports two parameters, start and end, to dynamically define the index position of the string.

Long_string = "To live is to learn,to learn is to better live" long_string.startswith ('To') long_string.startswith (' li', 3,5) long_string.endswith ('live') long_string.endswith (' live', 0,7)

Also supporting start and end to judge strings are .find (), .rfind () and .index (), .rindex ().

These two types of string addressing methods support left-to-right and right-to-left addressing methods, except that:

Find returns-1 when it is not found, while index throws an exception for ValueError when it is not found.

Long_string.index ('live') # 3 long_string.rindex (' live') # 42 string content change

In a narrow sense, the replacement of strings is done with .replace (), so why talk about it separately? Because it has an optional parameter count.

Long_string = "To live is to learn,to learn is to better live" long_string.count ('live') # 2 long_string.replace (' live','Live',1) output:'To Live is to learn,to learn is to better live' # you can see that the second live has not been replaced

I just said that in a narrow sense, what about in a broad sense?

1. (lstroke r) strip ()

Filter out the specific characters at the left, right, and both ends of the string, which defaults to spaces.

What strip () should note is that the characters in strip ('TolLive') do not match completely, but match for each character. To put it bluntly, go straight to the example:

Long_string = "To live is to learn,to learn is to better live" long_string.strip ('TolLive')' s to learn,to learn is to better'

two。 String slicing

The slicing of the string is divided into long_string [start:end;step] start, end interval is left closed and right open. This online said too much, and then pull it out to talk about it in detail will be beaten.

Just (width, [fillchar]), center (width, [fillchar]), zfill (width)

These are filled with fixed-length characters, using spaces by default (zfill means zero.) Well, you'll see what it means. There's no need to say any more. .

String formatted output

Fill and center could have been put here, but they were not qualified for frequency and heavyweight, so they were left on it.

There are two types of Python formatted output, which was in the age of pyton2, namely% and format. There are too many materials on these two kinds of Internet, and they don't seem to be forced to speak too much.

However, it is necessary to briefly talk about the special features.

1.% formatted output:

How can the output be regarded as a% symbol in the% format output? Use two percent signs (%)

% (-) (width) width is the set length, the left space is filled by default, and the-sign is filled right by default.

.width represents the string truncated and the length of the string retained.

Type% s string% d decimal integer% f decimal …

Multiple parameters are that the following parameters need to be wrapped in parentheses

'name:%-5s age:% 4d hobbies:% .8s'% ('Wang Dahun', 30 girls python, Java') output: 'name: Wang Dahe Age: 30 hobbies: python, J'

Output in 2.format format:

Since the beginning of python3, format has officially indicated that it will replace% of the output mode, and the reason why it still retains% is mainly for compatibility considerations.

In contrast to%, format uses curly braces {} to represent variables

< >

^ represents the alignment of format

'{:-^ 40s}' .format ('gorgeous split line') output:-gorgeous split line -'

3.f-string

When the version of Python3.6 is updated, f-string is added. For those who are good at English, you can see the official explanation of PEP 498-- Literal String Interpolation.

F-string is the use of string quotation marks preceded by f _ hand F and replaced with {} annotations.

The official launch of f-string is mainly due to its higher performance and stronger functions. Here's an example:

Name = 'Uranus' f'Hello, {name}' f'Hello, {name.lower ()} 'f'Hello, {name: ^ 10s}' f'Hello, {(lambda x: Xero2) (name)} 'output:' Hello,Uranus' 'Hello,uranus'' Hello,Uranus' 'Hello,UranusUranus', thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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