The most complete history python string Guide

Appalling

Come up with housekeeping old Chinese advertising field, failed to save the dismal selenium episodes. On Friday talking with friends, he said he hoped to see some basic knowledge python. Would also have to worry about updating basic things no one, but it appears that the worst of the series but selenium ... ha ha.
Although updated basics, but the basic things is not important or that does not mean you will not believe walked ...
I remember saying comes to, when one thing please encountered regular, that it becomes two things. See this sentence, you think I want to say python regular? NO ...
everyday coding, you will find that too often we need to process the data, and this data whether arrays, lists, dictionaries, ultimately can not escape manipulating strings.
So today to talk with you divergent strings!

Defined strings

Over, it estimated that many people will see this title off the page, and may wish to wait and see down?
python-defined character string is not as strict java, whether single quotes, double quotes, or even three single and double quotes can be used to define the character (string), as long as you can in pairs. such as:

# 单个字符
a='a'
# 使用单引号定义字符串
name='Uranus'
# 使用双引号定义字符串
code = "Hello World ..."
# 既然说到了string,怎么能不点开源码看看呢?
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'.
    """

Though these are not major said, but still under the simple mention three single or double quotes, primarily used as documentation comments, please do not bring definition string (although this syntax error and will not appear).
Today mainly referring to the next section on how to play the strings should be defined, PEP8 provisions, the length of the line of code not exceed 120 characters. So if this is the case, how to do?

# 不推荐的使用方式:
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.
"""
# 或者这样
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."
# 更好的实现方式:
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."
        )

String simple .is () and. () Usage

.is () *, since it is is, it returns the result of only two, True or False
the first to compare the numbers:

isdigit ()
True: the Unicode number, byte number (one byte), digital full-width (two-byte), Roman numerals
False: Digital Character
Error: None

isdecimal ()
True: the Unicode digital, digital full-width (two-byte)
False: Roman numerals, characters Digital
Error: byte number (one byte)

IsNumeric ()
True: the Unicode digital, digital full-width (two-byte), Roman numerals, characters digital
False: None
Error: byte number (one byte)

Summarizes several loopholes knowledge:

a='①②③④⑤'
isdigit()、isnumeric() 为True isdecimal()为False
b='一壹'
isnumeric()会认为是True的哦!

 A look equation:

isalnum () = isdigit () + the isalpha () + isspace becomes ()
isdigit () indicates the number of strings all
the isalpha () represents all the character string
isspace becomes () indicates a string of one or more of spaces
isalnum ( ) represents all within the string of numbers and characters

a='12345'
b='①②③④⑤'
c='abc123'

print(a.isdigit()) # True
print(b.isalpha()) # True
print(c.isalnum()) # True

 For the case of the string method:

.isupper () string all uppercase composed
.islower () string consisting entirely of lowercase
.istitle () is a string camelCase, eg: "Hello World"

These usage removed is, it becomes a character string corresponding forwarding method. Studies will be set two, buy one get one ....

Without a final say. The is * --- isinstance (obj, type)

A judge what type of object ...
type Optional type: int, float, bool, complex , str, bytes, unicode, list, dict, set, tuple
and type can be one of the original group: isinstance (obj, (str , int))

Analyzing the content of the string

. * With () starts ends at the beginning of the end of the match not only support, but also support the start and end position of the two parameters to index dynamically defined strings

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 supports start, end determines there .find string () ,. rfind () and .index () ,. rindex ()
This method of addressing two strings are supported from left to right, right to left two addressing mode, except that:
the find when not found, -1 is returned, and when the index is not found, it will throw an exception ValueError of ...

long_string.index('live') # 3
long_string.rindex('live') # 42

Contents of the string changes

Use a narrow sense, the replacement string using .replace () can be, then why do you say alone? Because it has an optional parameter you 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'
# 可以看到,第二个live并未进行替换

Just say the narrow sense, so broad it?

(l / r) strip ()
specific character string left and right ends of the filter out, space ... default
Strip () where is to be noted that, strip the character ( 'TolLive') is not a complete match, but rather for each character match, said mixed up, directly on the examples:

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'

String sections

Slice the string into long_string [start: end; step] start, end interval close left right open ... the Internet, said too much, and then pull out a detailed talk will be beaten up ...

(l / r) just (width , [fillchar]), center (width, [fillchar]), zfill (width)
characters which are filled with a fixed length, the default spaces (zfill left complement 0, z is zero in meaning ...), meaning to see to understand, not to speak more ....

String formatted output

Originally fill and center and so can be placed here, but their frequency of use and heavyweight qualify, you throw on top of.
Python formatted output into two categories, it was in the era of pyton2, namely% and format. Both too much information online, said too much force did not seem grid ...
but, still want to speak briefly in which special place
% formatted output:

  • How% of output format, the output used to be seen as marked as the% sign it? Use two percent signs (%%)

  • % (-) (width) width to length is provided, with spaces left by default, add - right padding No.

  • .width representatives string truncation, how much the string length of retention

  • type% s% d string decimal decimal integer% f ...

  • A plurality of parameters, the parameters to be used later wrapped in parentheses

'姓名:%-5s 年龄:%4d 爱好: %.8s' % ('王大锤',30,'python、Java')
output:
'姓名:王大锤   年龄:  30 爱好: python、J'

format output format:
format at the start of the official says that the replacement python3% of output, the reason retained%, mainly for compatibility ...

  • Comparative%, format using braces {} represent variables

  • <> ^ Represents the format of alignment

'{:-^40s}'.format('华丽的分割线')
output:
'-----------------华丽的分割线-----------------'

f-string
when the updated version Python3.6, added f-string, with good English can go to the official explanation PEP 498 - Literal String Interpolation.
f-string is a quoted string before starting with / f F, and denoted by {} use forms using the replacement position.
The reason why the official launch of the f-string, mainly because of its higher performance and greater functionality. Examples go from:

name = 'Uranus'
f'Hello,{name}'
f'Hello,{name.lower()}'
f'Hello,{name:^10s}'
f'Hello,{(lambda x: x*2) (name)}'

output:
'Hello,Uranus'
'Hello,uranus'
'Hello,  Uranus  '
'Hello,UranusUranus'

How to say, a number of high-end, but my people are a little nostalgic ah ...

The End

String manipulation, what? There are too many things to be touched by side, but write down at first light tomorrow but also how to work, the assessments the assessments ...
today's content on here, if that helps, welcome to my articles or micro letter No public 【清风Python】share to more people like python, thank you.

Source:  breeze Python   Author: Wang Xiang

 

Guess you like

Origin blog.csdn.net/devcloud/article/details/94598372