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

Python learning 2: String

編輯:Python

List of articles

  • One 、 String encoding conversion
    • 1.1 Use encode() Method code
    • 1.2 Use encode() Method decoding
  • Two 、 String general operation
    • 2.1 String concatenation
    • 2.2 Calculate the length of the string
    • 2.3 Intercepting string
    • 2.4 Division 、 Merge strings
      • Division
      • Merge
    • 2.5 Retrieve string
      • Method 1 :count() Count the quantity
      • Method 2 :find() Calculation location
      • Method 3 :in Determine the position
      • Method four :index() Methods and find equally , It's just that there is no exception thrown
      • Method five :startswitch() Method return Ture perhaps False
      • Methods six :endswitch() Method return Ture perhaps False
    • 2.6 Case conversion of letters
      • Capitalize to lowercase lower() Method , Small to capital upper()
      • 2.7 Remove empty strings and special strings from strings
        • Method 1 :strip()
        • Method 2 :lstrip()
        • Method 3 :rstrip()
      • 2.8 Formatted string
        • 1. Use % Operation symbol
        • 2.format Format function

One 、 String encoding conversion

1.1 Use encode() Method code

str=encode([encoding="utf-8]"[,error="strict"])
The default is utf-8 If you want to use simplified Chinese, you can also use gb2312
strict: Throw an exception when you encounter an error
It can also be ignore( Ignore ) It can also be replace
if __name__ == '__main__':
value=' Hello , I am a code ronin , Waves inside waves '
byte=value.encode('GBK')
print(value)
print(byte)
》》》
Hello , I am a code ronin , Waves inside waves
b'\xc4\xe3\xba\xc3\xa3\xac\xce\xd2\xca\xc7\xb4\xfa\xc2\xeb\xc0\xcb\xc8\xcb\xa3\xac\xc0\xcb\xc0\xef\xc0\xcb'

1.2 Use encode() Method decoding

str=decode([encoding="utf-8]"[,error="strict"])
The default is utf-8 If you want to use simplified Chinese, you can also use gb2312
strict: Throw an exception when you encounter an error
It can also be ignore( Ignore ) It can also be replace
if __name__ == '__main__':
value=' Hello , I am a code ronin , Waves inside waves '
byte=value.encode('GBK')
print(value)
print(byte)
print(byte.decode('GBK'))
》》》
Hello , I am a code ronin , Waves inside waves
b'\xc4\xe3\xba\xc3\xa3\xac\xce\xd2\xca\xc7\xb4\xfa\xc2\xeb\xc0\xcb\xc8\xcb\xa3\xac\xc0\xcb\xc0\xef\xc0\xcb'
Hello , I am a code ronin , Waves inside waves

Two 、 String general operation

2.1 String concatenation

Use the plus sign directly ( Same type , Different types will report errors )

if __name__ == '__main__':
value1=" Hello "
value2=123
print(value1+value2)

2.2 Calculate the length of the string

Chinese characters are in GBK/GB2312 Coding 2 Bytes
stay UTF-8.uncode Occupy 3 Bytes ( perhaps 4 Bytes )

The calculated length provides len(string) Function calculation method


if __name__ == '__main__':
value1=" Hello "
print(len(value1))
print(len(value1.encode('GBK')))
》》》
2
4

2.3 Intercepting string

string[startstep]
start: Starting position , The default is 0
end: End position , It doesn't contain
step: step , The default is 1

if __name__ == '__main__':
value1=" Hello 345678"
print(value1[2:])
print(value1[:2])
print(value1[0:8:2])
》》》
345678
Hello
you 357

2.4 Division 、 Merge strings

Division

str.split(sep,maxsplit)
str: String to split
sep: Specify the separator , The default is None
maxsplit: Optional parameters , The default is -1-> Number of divisions

Merge

strnew=str.join(iterable)
strnew: New string
string: Separator for merging
iterable: Iteratable object , Concatenate all elements in the iteration object according to separate strings


list_str=[' I ',' Love ',' you ']
list_new='*'.join(list_str)
print(list_new)
》》》
I * Love * you

2.5 Retrieve string

Method 1 :count() Count the quantity

str.count(sub[,start[,end]])

str Retrieved string
sub: Substring to be retrieved
start: Starting position
end: End position

str='123456'
print(str.count(6))
》》》
1

Method 2 :find() Calculation location

str.find(sub[,start[,end]])

str Retrieved string
sub: Substring to be retrieved
start: Starting position
end: End position

str='123456'
print(str.find(6))
》》》
5

Method 3 :in Determine the position

if __name__ == '__main__':
list_str=[' I ',' Love ',' you ']
print(' Love ' in list_str)
》》》
True

Method four :index() Methods and find equally , It's just that there is no exception thrown

str.index(sub[,start[,end]])

str Retrieved string
sub: Substring to be retrieved
start: Starting position
end: End position

Method five :startswitch() Method return Ture perhaps False

str.startswitch(prefix[,start[,end]])

str Retrieved string
prefix: Substring to be retrieved
start: Starting position
end: End position

if __name__ == '__main__':
list_str=[' I ',' Love ',' you ']
print(list_str.startswitch(' I '))
》》》
True

Methods six :endswitch() Method return Ture perhaps False

str.endswitch(prefix[,start[,end]])

str Retrieved string
prefix: Substring to be retrieved
start: Starting position
end: End position


if __name__ == '__main__':
list_str=[' I ',' Love ',' you ']
print(list_str.endswitch(' you '))
》》》
True

2.6 Case conversion of letters

Capitalize to lowercase lower() Method , Small to capital upper()

if __name__ == '__main__':
str='ABC'
print(str.lower())
str='abc'
print(str.upper())
》》》
abc
ABC

2.7 Remove empty strings and special strings from strings

Method 1 :strip()

str.strip([char])// The default is to remove the leading and trailing empty characters and special strings ,char It's optional , More than one... Can be specified

Method 2 :lstrip()

str.lstrip([char])// The default is to remove empty characters and special strings on the left ,char It's optional , More than one... Can be specified ,

Method 3 :rstrip()

str.rstrip([char])// The default is to remove empty characters and special strings on the right ,char It's optional , More than one... Can be specified

2.8 Formatted string

1. Use % Operation symbol

Python Support output of formatted string . Although this may use very complex expressions , But the most basic use is to insert a value into a string formatter %s In the string of .

print (" My name is %s This year, %d year !" % (' Xiao Ming ', 10))
My name is Xiao Ming This year, 10 year !


Formatting operator helper :

2.format Format function

Python2.6 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

>>>"{} {}".format("hello", "world") # Does not set the specified location , By default
'hello world'
>>> "{0} {1}".format("hello", "world") # Set the specified location
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # Set the specified location
'world hello world'

You can also set parameters

# -*- coding: UTF-8 -*-
print(" The websites :{name}, Address {url}".format(name=" Novice tutorial ", url="www.runoob.com"))
# Set the parameters through the dictionary
site = {"name": " Novice tutorial ", "url": "www.runoob.com"}
print(" The websites :{name}, Address {url}".format(**site))
# Set the parameters by the list index
my_list = [' Novice tutorial ', 'www.runoob.com']
print(" The websites :{0[0]}, Address {0[1]}".format(my_list)) # "0" Is a must
The websites : Novice tutorial , Address www.runoob.com
The websites : Novice tutorial , Address www.runoob.com
The websites : Novice tutorial , Address www.runoob.com

Also you can ask the str.format() The incoming object :


class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('value by : {0.value}'.format(my_value)) # "0" It's optional

Numbers

>>> print("{:.2f}".format(3.1415926))
3.14


In addition, we can use braces {} To escape braces , The following example :


print ("{} The corresponding position is {
{0}}".format("runoob"))
》》》
runoob The corresponding position is {0}

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