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

Application of Python common strings

編輯:Python

List of articles

  • One 、 String Introduction
      • 1. Create string
      • 2. Python String update
      • 3. Python Escape character
  • Two 、 String output and input
      • 1. String output
      • 2. Input of string
  • 3、 ... and 、 Access the value in the string
      • 1. storage
      • 2. Character slices
  • Four 、 String built-in functions
      • 1. find function
      • 2. index function
      • 3. count function
      • 4. replace function
      • 5. split function
      • 6. capitalize、title 、upper、lower function
      • 7. startwith 、endswith function
      • 8. ljust、rjust function
      • 9. center function
      • 10. lstrip function
      • 11. encode function
      • 12. strip function
      • 13. format function
  • 5、 ... and 、 String operators

One 、 String Introduction

A string is an array of sequential characters , And write it in single quotation marks , In double or triple quotation marks . in addition ,Python There is no character data type , So when we write “ a” when , It will be considered to be of length 1 String .

 Single quotation marks [' ']
Double quotes [" "]
Three quotes [''' ''']

1. Create string

Creating a string is simple , We can use quotation marks ( ’ or " ) To create a string , Just assign a value to the variable . for example :

a = 'Hello'
print(a)
b = "Hello"
print(b)
c ='''Hello
How is the whether today? '''
print(c)
# Output results 
Hello
Hello
Hello
How is the whether today?
  • When we use both single and double quotation marks in a string and write multiple lines of sentences , Three quotation marks are usually used
  • When using single quotation marks , String should not contain single quotes , Because if that happens ,Python It is assumed that the line ends with the second quotation mark itself , And don't get the output you need
  • Double and triple quotation marks should be added after the same symbol

2. Python String update

You can intercept a part of the string and splice it with other fields , as follows :

a='hello world'
print(a)
print(' Updated string :',a[:6] + 'how are you')
# The results are as follows 
hello world
Updated string : hello how are you

3. Python Escape character

Escape character describe \ ( When at the tail ) Line continuation operator \ Backslash notation \’ Single quotation marks " Double quotes \n Line break \b Backspace \t Horizontal tabs \r enter , take \r The following moves to the beginning of the string , And replace the characters at the beginning one by one , Until \r The following content is completely replaced

demonstration :

------------------------------------------------( Cross row output )----------------------------------------
print("line1 \ line2 \ line3")
# The results are as follows 
line1 line2 line3
------------------------------------------------( Line break )-------------------------------------------
print("hello\nworld")
# The results are as follows 
hello
world
------------------------------------------------( Horizontal tabs )---------------------------------------
print("hello \tworld")
# The execution process is as follows 
hello world
------------------------------------------------( Replace )----------------------------------------
print("hello\rworld")
# The execution process is as follows 
world
print('google runoob taobao\r123456')
# The execution process is as follows 
123456
------------------------------------------------( Backspace )----------------------------------------
print("hello\bworld")
# The execution process is as follows 
hellworld

Two 、 String output and input

1. String output

Output multiple times in the following code " I this year XX year ", Only one xx The content of the representative is changing , Just imagine , Is there a way to simplify the procedure ?

print(" I this year 10 year ")
print(" I this year 11 year ")
print(" I this year 12 year ")

We can do this through string formatting , As shown below

print(" My name is %s, This year, %d year !" % (' Xiao Ming ',10))
# Output results 
My name is Xiao Ming , This year, 10 year !
a=" my "
b=" Motherland "
print(" I love you! ,%s,%s"%(a,b))
# Output results 
I love you! , my , Motherland

Common formatting symbols

Symbol explain %s character string %d Signed decimal integers %f Floating point real

2. Input of string

Python3 Provides input Function reads a line of text from standard input , The default standard input is the keyboard .

  • input Can receive a python Expression as input , And return the result to .
user_name=input(" Please enter a user name :")
print(user_name)
# Output results 
Please enter a user name : Zhang San
Zhang San

3、 ... and 、 Access the value in the string

1. storage

Each character of the string corresponds to a subscript , Subscript number from 0 Start

Example

a="hello,this is a apple"
print(len(a))
# Output results 
21

2. Character slices

What is slicing ? The syntax format of the slice is as follows :

[ start : end : step ]

The section selected by the slice belongs to the left closed right open type , From “ start ” Bit start , To “ end ” The last one of the first ( Does not include the end bit itself )

  • Use slice to intercept string
a="Hello,this is a super man."
print(len(a))
print(a[5]) #a[5] Indicates that the subscript in the string is 5 The characters of , The first 6 Characters 
print(a[5:10]) #a[5:10] Represents that the subscript in the string is from 5 To 9 The characters of , That is to say 6 One to the first 10 Characters , barring 10
print(a[5:10:2]) #a[5:10:2] Represents that the subscript in the string is from 5 To 9 The characters of , One before every two , That is to say 6,8,10 The characters of 
# Output results 
26
,
,this
,hs

Assuming a string name=“abcdef”, be

name[0:3] ———— abc # from 0 Start to 2 Value 
name[3:5] ————de # from 3 Start to 4 Value 
name[1:-1]————bcde #1 From the first ,-1 Take from the back to the front , Not including the last one 
name[2:] ————cdef # From 2 From the beginning to the end 
name[::-2]————fdb # From the back to the front , In steps of 2

Four 、 String built-in functions

Common operations for strings are as follows

  • increase ——》 Add... In front , Add... At the back , Add... In the middle
  • Delete ——》 You can't delete it until you find it
  • Change ——》 Find it before you change it
  • check ——》 length 、 section 、 Whether it contains characters 、 Whether to include substring , Where are the characters

1. find function

Check whether the string contains substrings

str.find(sub[,start[,end]])
# The parameters are as follows :
sub——》 Specifies the string to retrieve
start——》 Start index , The default is 0
end——》 End index , The default is the length of the string

Example :

a="Hello,I'm guyu"
b="Hello"
c="I'm guyu"
print(a.find(b))
print(a.find(c))
print(b.find(c))
# Output results 
0
6
-1

2. index function

Check whether the string contains substrings

str.index(sub[,start[,end]])
# The parameters are as follows 
sub——》 Specifies the string to retrieve
start——》 Start index , The default is 0
end——》 End index , The default is the length of the string
a="Hello,I'm LiLei"
b="Hello"
c="I'm LiLei"
print(a.index(b))
print(a.index(c))
print(b.index(c)) # Because if you can't find it, you will report an error 
# Output results 
0
6
Traceback (most recent call last):
File "E:/PycharmProjects/str_2022.0115/str/transform.py", line 69, in <module>
print(b.index(c))
ValueError: substring not found

PS:find and index Almost the same in function , however find If it is not found, it will return a -1 , and index If it cannot be found, an error will be reported directly

3. count function

Count the number of characters in a string

str.count(sub[,start[,end]])
# The parameters are as follows 
sub——》 Search for substrings
start——》 Where the string starts searching
end——》 Where the string ends the search

Example :

a="Hello,I'm LiLei"
print(a.count("m",9))
print(a.count("m",8)) # From 8 Start looking for ,m The subscript of is 8, So we can find 
print(a.count("m",8,1)) # If the actual subscript is larger than the ending subscript , Is equivalent to an empty string 
# Output results 
0
1
0
PS: If there are multiple matches , Only the first matching position will be returned

4. replace function

Replace the old string with the new string

str.replace(old,new[,count])
# The parameters are as follows 
old——》 Replaced string
new——》 Replace with a new string
count——》 Optional parameters , Replace no more than count Time .0

Example :

a="Hello,I'm LiLei,How are you! Hello"
b="Hello"
c="I'm LiLei"
print(a.replace("LiLei","lisi")) # hold LiLei Replace with lisi 了 
print(a.replace(b," Hello ")) # hold b Defined Hello, stay a All have been replaced in 
print(a.replace(b," Hello ",1)) # Replace only once , Replace the previous one first 
# Output results 
Hello,I'm lisi,How are you! Hello Hello ,I'm LiLei,How are you! Hello
Hello ,I'm LiLei,How are you! Hello

5. split function

Slice a string by specifying a separator

str.split(sep=None,maxsplit=-1)
# The parameters are as follows 
sep——》 Separator , The default is all empty characters
maxsplit——》 Number of divisions

Example :

a="Hello,I'm LiLei,How are you! Hello"
print(a.split(",")) # Separate with commas 
print(a.split(",",1)) # Specify the number of splits as 1 Time 
# Output results 
['Hello', "I'm LiLei", 'How are you! Hello']
['Hello', "I'm LiLei,How are you! Hello"]

6. capitalize、title 、upper、lower function

capitalize: The first character is capitalized , Other characters are lowercase

str.capitalize()

title: All words are capitalized , The rest of the letters are lowercase

str.title()

upper: All characters are capitalized

str.upper()

lower: All characters are lowercase

str.lower()

Example :

a="hello,i'm lilei,how are you! hello"
print(a.capitalize()) # The first letter is capitalized 
print(a.title()) # Capitalize the first letter after the space and symbol , Other lowercase 
print(a.upper()) # All are capitalized 
print(a.lower()) # All lowercase 
# Output results 
Hello,i'm lilei,how are you! hello Hello,I'M Lilei,How Are You! Hello
HELLO,I'M LILEI,HOW ARE YOU! HELLO hello,i'm lilei,how are you! hello

7. startwith 、endswith function

startwith: Check whether the string starts with the specified string
endswith: Check whether the string ends with the specified string

str.startswith(prefix[,start[,end]])
# The parameters are as follows 
prefix——》 Detected string
start——》 Optional parameters , The starting position of string detection
end——》 Optional parameters , End position of string detection

Example :

a="hello,i'm lilei,how are you! Hello"
print(a.startswith("hello",0))
print(a.startswith("Hello"))
print(a.startswith("Hello",29))
print(a.endswith("Hello"))
print(a.endswith("hello"))
print(a.endswith("hello",0,5)) #0,5 Indicates the search start subscript 0 And end subscript 5
# Execution results 
True
False
True
True
False
True

8. ljust、rjust function

Align left , Fill a new string with spaces to the specified length
Right alignment , Fill a new string with spaces to the specified length

str.ljust(width[,fillchar])
str.rjust(width[,fillchar])
# The parameters are as follows 
width——》 Specifies the length of the string
fillchar——》 Fill character , Default is space

Example :

b="Hello"
print(b.ljust(10,','))
print(b.rjust(10,','))
# Execution results 
Hello,,,,,
,,,,,Hello

9. center function

Returns a length of width And centered string

str.center(width[,fillchar])
# The parameters are as follows 
width——》 Specifies the length of the string
fillchar——》 Fill character

Example :

b="Hello"
print(b.center(10,'_')) # Put the string in the middle , Left and right _ Fill to 10 A space 
# Execution results 
__Hello___

10. lstrip function

Intercept the space to the left of the string or the specified character

str.lstrip([chars])
# The parameters are as follows 
chars——》 Specify the characters to intercept

Example :

c=" I'm LiLei "
print(c.lstrip()) # There are spaces on the left and right , Only the left 
print(c.rstrip()) # There are spaces on the left and right , Only the one on the right is removed 
print(a.rstrip('Hello')) # You can also remove the specified string 
# Execution results 
I'm LiLei I'm LiLei
hello,i'm lilei,how are you!

11. encode function

Format

encode(encoding='UTF-8',errors='strict')

With encoding The specified encoding format encodes the string , If there is an error, one will be reported by default ValueError It's abnormal , Unless errors Specifies the ’ignore’ perhaps ’replace’

Example :

b=" Hello "
print(b.encode("UTF-8"))
print(b.encode("GBK"))
# Execution results 
b'\xe4\xbd\xa0\xe5\xa5\xbd'
b'\xc4\xe3\xba\xc3'

12. strip function

Delete the characters specified at the beginning and end of the string

str.strip([chars])
# The parameters are as follows 
chars——》 Remove the characters specified at the beginning and end of the string

Example :

a="hello,i'm lilei,how are you! Hello"
print(a.strip('hello'))
# Execution results 
,i'm lilei,how are you! H

13. format function

python2.6 Version start , Added a function to format strings str.format(), It enhances string formatting The basic grammar is through {} and :
To replace the old % format Function can take any number of arguments , Positions can be out of order

Example
① The specified location

print("{} {}".format("hello","world")) # No location , By default 
print("{0} {1}".format("hello","world")) # The specified location 
print("{1} {0}".format("hello","world"))
print("{1} {0} {1}".format("hello","world"))
# Execution results 
hello world
hello world
world hello
world hello world

② Set the parameters through the dictionary

site={
"name":" Baidu ","url":"www.baidu.com"}
print(" The websites :{name}, Address :{url}".format(**site))
# Execution results 
The websites : Baidu , Address :www.baidu.com

③ Set the parameters by the list index

my_list=[" Baidu Encyclopedia ","www.baidu,com"]
print(" The websites :{0[0]}, Address :{0[1]}".format(my_list))
# Execution results 
The websites : Baidu Encyclopedia , Address :www.baidu,com

5、 ... and 、 String operators

The operator describe + String connection * Repeat output string [] Get the characters in the string by index [:] To intercept a part of a string

Example

a="hello"
b="world"
print(a+b)
# Output results 
helloworld
------------------------------------------------------------------------------------------------
a="hello"
print(a*3)
# Output results 
hellohellohello
------------------------------------------------------------------------------------------------
a="hello"
b="world"
print(a[1])
# Output results 
e
------------------------------------------------------------------------------------------------
a="hello"
b="world"
print(a[1:3]) # Subscript 1 To 3 Value , barring 3
# Output results 
el

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