程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python string types and Applications

編輯:Python

character string : Orderly , Immutable , A sequence enclosed in quotation marks .
Let's start with placeholders :
%s String placeholder
%d Digital placeholders
%f Floating point number placeholder
%.2f Controls floating point number placeholders
give an example : Use of placeholders

print('this %s age is %d years old'%('boy',21))
> this boy age is 21 years old

%f Floating point number placeholder

print('the boy height is %f m'%(1.8))
>>>the boy height is 1.800000 m

We need to control the number of decimal places after the height , You need placeholders to control floating-point data %.2f.

print('the boy height is %.2f m'%(1.8))
>>>the boy height is 1.80 m

String truncation : character string [start:end], The head is not the tail .
for example :

str_name = 'beautiful'
print(str_name[1:3])
>>>ea

adopt str_name[1:3], from ’beautiful’ First letter of ( Starting from scratch )e To the first (end-1) position , That is the end of the second , Include the preceding numbers , But it does not include the following . If the string contains spaces , Spaces also occupy one character bit .
Step size truncation of string : character string [startstep], It is the same as Baotou without Baowei .
for example :

str_name = 'beautiful'
print(str_name[1:5:1])
>>>eaut

Here you can see , There seems to be no step size to intercept characters , This is because the step size is (|step|-1), The code step shown above is one , And the actual value 1-1=0.

str_name = 'beautiful'
print(str_name[1:9:2])
>>>euiu

When step>0 when , The string is truncated from left to right , Above
When step<0 when , The string is also truncated from left to right , Just intercept the string in reverse . The following code :

str_name = 'beautiful'
print(str_name[4:6:-1])

The program stops running , No results . here step<0, My understanding is that it is equivalent to reversing the string , But the subscript of the string is the original , At the same time, string str_name The start and end bits of are also interchangeable , So this is equivalent to 4 As of ,6 As the starting point , The start is greater than the end , The program cannot run naturally , When we swap the two ,

str_name = 'beautiful'
print(str_name[6:4:-1])
>>>fi

here , Demonstrate the results through the above code , It can be seen that the intercepted string should end from the sixth bit ( That is, the seventh character , Contains the seventh character , Step size is negative , At the same time, the starting position is the fourth , That is, the fifth character , It doesn't contain , The head and tail can only cover one ), That is to say beautif, Start with the sixth character , The only characters actually intercepted are if, Because the step size is negative , So the reverse intercepts , In the end fi.

How to find a string
count Counting function , Returns the number of characters in a string
find lookup , Returns the index of the first custom character from the left , No return found -1
rfind lookup , Returns the index of the first custom character from the right , No return found -1
index lookup , Returns the index of the first custom character from the left , No error found
rindex lookup , Returns the index of the first custom character from the right , No error found

str_test = 'hello world'
print(str_test.count('l'))
print(str_test.find('e'))
print(str_test.find('p'))
print(str_test.index('p'))
>>>3
1
-1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-24-c1134bdadc14> in <module>
3 print(str_test.find('e'))
4 print(str_test.find('p'))
----> 5 print(str_test.index('p'))
ValueError: substring not found

Segmentation of strings
partition hold mystr With str Divided into three parts ,str front ,str Self and str after

str_test = 'hello world'
print(str_test)
print(str_test.partition('o'))
>>>hello world
('hell', 'o', ' world')

such , adopt print(str_test.partition(‘o’)), Make the string from ’o’ Divided into three parts .

rpartition Be similar to partition() function , It's just from the right .
str_test = 'hello world'
print(str_test)
print(str_test.rpartition('o'))
>>>hello world
('hello w', 'o', 'rld')
splitlines Separate by lines , Returns a list of rows as elements , Split by newline
str_test = 'hello\n world\n python\n'
print(str_test)
print(str_test.splitlines())
>>>hello
world
python
['hello', ' world', ' python']

Judge the segmentation of the string by reading the newline character .

split Determine the separator slice of the string
Just every other delimiter , Split the string

String replacement
replace Replace the specified element from left to right , You can specify the number of replacements , Replace all by default .

str_test = 'hello world python'
print(str_test)
print(str_test.replace('o','a'))

hello world python
hella warld pythan

In this way, the characters o, Replace all with a.
String decoration
center Center the string at the specified length , If it cannot be centered, the left is short and the right is long , Fill content can be specified , By default, it is filled with spaces
ljust Make the string left aligned at the specified length , Fill content can be specified , By default, it is filled with spaces
rjust Make the string right aligned at the specified length , Fill content can be specified , By default, it is filled with spaces
zfill Fill the string to the specified length , Not enough space for 0 Start from the left and add
format In order , Pass the following arguments to the preceding braces
strip By default, the spaces on both sides are removed , Removal of content can specify
rstrip By default, the right space is removed , Removal of content can specify
lstrip The left space is removed by default , Removal of content can specify

str_test = ‘for’
print(str_test.center(10))
#center Two parameters can be added to this
print(str_test.center(10,‘x’))
The operation results are as follows :
for
xxxforxxxx
ljust Two parameters can be added to this
print(str_test.ljust(10))
print(str_test.ljust(10,‘x’))
print(str_test.rjust(10,‘x’))
The operation results are as follows :
for
forxxxxxxx
xxxxxxxfor
print(str_test.zfill(10))
The operation results are as follows :
0000000for
Be careful : If the size passed in is less than the length of the string , The string doesn't change .
str_test = ’ for ’
print(str_test.strip())
‘for’
print(str_test.rstrip())
’ for’
print(str_test.lstrip())
'for ’
python = “{0} is {1}”
print(python.format(‘for’,‘cool’))
The operation results are as follows :
‘for is cool’

Deformation of strings

upper Converts all letters in a string to uppercase
lower Converts all letters in a string to lowercase
swapcase Swap the case of all letters in the string
title Capitalize the first letter of a word in a string character , Words are divided by non alphabets
capitalize Only the first letter of the string is capitalized
expandtabs Put... In the string tab Symbol (’\t’) Turn to space ,tab
Symbol (’\t’) The default number of spaces is 8, You can try 8,12

String judgment

isalnum Determine whether a string is composed entirely of letters or numbers
isalpha Determine whether the string is completely composed of letters
isdigit Determine whether the string is completely composed of numbers
isupper Determine whether the letters in the string are completely capitalized
islower Determine whether the letters in the string are completely lowercase
istitle Determine whether the string meets the title Format
isspace Determine whether the string is completely composed of spaces
startswith Determine the beginning character of the string , You can also intercept and judge
endswith Determine the end character of the string , You can also intercept and judge

# Determine whether a string is composed entirely of letters or numbers 
print('12345a'.isalnum())
# Determine whether the string is completely composed of letters 
print('abcdef'.isalpha())
# Determine whether the string is completely composed of numbers 
print('12345'.isdigit())
# Determine whether the letters in the string are completely capitalized 
print('HELLO'.isupper())
# Determine whether the letters in the string are completely lowercase 
print('hello'.islower())
# Determine whether the string meets the title Format 
print('Hello'.istitle())
# Determine whether the string is completely composed of spaces 
print(' '.isspace())
# Determine the beginning character of the string , You can also intercept and judge 
print('for is long'.startswith('f'))
print('for is long'[3:].startswith('f'))
# Determine the end character of the string , You can also intercept and judge 
print('for is long'.endswith('long'))

python The variables in the are as follows :
The above is related to self-study python Some notes on string related content , Part of the content comes from the Internet , If there are errors , Please point out .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved