VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • Python:字符串

字符串

字符串:一个有序的字符集合,用来存储和表现基于文本的信息,要求使用单引号或双引号括起来。使用双引号的一个好处,就是字符串中可以使用单引号字符。例如:

python
>>> a="I'm a dog."
>>> a
"I'm a dog."
>>> a='I'm a dog.'
  File "<stdin>", line 1
    a='I'm a dog.'
         ^
SyntaxError: invalid syntax

字符串是“不可变的”,它不能被更改。尝试对字符串中的一个字符重新赋值,将导致TypeError错误。例如:

python
>>> a=r"It's a cat"
>>> a[5]='an'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

转义

反斜杠\可以用来转义

python
>>> 'desn't'
  File "<stdin>", line 1
    'desn't'
          ^
SyntaxError: invalid syntax
>>> 'desn\'t'
"desn't"

如果你不希望前置了\的字符转义成特殊字符,可以使用原始字符串 方式,在引号前添加r即可:

python
>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
C:\some\name

按下标取值

字符串是可以被索引(下标访问)的,第一个字符索引是0。单个字符并没有特殊的类型,只是一个长度为一的字符串。

python
>>> a="hello world!"
>>> a[1]
'e'
>>> a[5]
' '

切片

python
>>> a="hello world!"
>>> a[3:7]
'lo w'

长度

python
>>> a="hello world!"
>>> len(a)
12

in和not in

python
>>> a="hello world!"
>>> 'a' in a
False
>>> 'e' in a
True
>>> 'a' not in a
True

跨行连续输入

字符串字面值可以跨行连续输入。一种方式是用三重引号:"""..."""'''...'''。字符串中的回车换行会自动包含到字符串中,如果不想包含,在行尾添加一个\即可。

python
>>> print("""\
... Usage: thingy [OPTIONS]
...      -h                        Display this usage message
...      -H hostname               Hostname to connect to
... """)
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

拼接

字符串可以用+进行连接,也可以用*进行重复。

python
>>> a='haha'
>>> b='lala'
>>> a+b
'hahalala'
>>> a*3
'hahahahahaha'

相邻的两个或多个字符串字面值(引号引起来的字符)将会自动连接到一起。

python
>>> 'hi''story'
'history'

# 只能对两个字面值这样操作,变量或表达式不行
>>> c='hi'
>>> c'story'
  File "<stdin>", line 1
    c'story'
     ^
SyntaxError: invalid syntax

# 如果想连接变量,或者连接变量和字面值,可以用 + 号
>>> c+'story'
'history'

字符串的方法

转换大小写

upper()和lower()字符串方法返回一个新字符串,其中原字符串的所有字母都被相应地转换为大写或小写。字符串中非字母字符保持不变。

python
>>> a = 'Hello world!'
>>> a.upper()
'HELLO WORLD!'
>>> a.lower()
'hello world!'

Tips:这些方法没有改变字符串本身, 而是返回一个新字符串。如果你希望改变原来的字符串, 就必须在该字符串上调用upper()lower(),然后将这个新字符串赋给保存原来字符串的变量,如a=a.upper()

判断大小写

如果字符串至少有一个字母, 并且所有字母都是大写或小写,isupper()islower()方法就会相应地返回布尔值True。否则, 该方法返回False

python
>>> a = 'Hello world!'
>>> a.isupper()
False
>>> a.islower()
False
>>> b='a dog'
>>> b.islower()
True
>>> b.isupper()
False
>>> c='AAA'
>>> c.isupper()
True
>>> c.islower()
False

isX字符串方法

除了islower()isupper(), 还有几个字符串方法,它们的名字以is开始。下面是一些常用的isX字符串方法:

  • isalpha()返回True,如果字符串只包含字母,并且非空;
  • isalnum()返回True,如果字符串只包含字母和数字,并且非空;
  • isdecimal()返回True,如果字符串只包含数字字符,并且非空;
  • isspace()返回True,如果字符串只包含空格、制表符和换行,并且非空;
  • istitle()返回True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词;

判断开始的字符串和结束的字符串

startswith()endswith()方法返回True,如果它们所调用的字符串以该方法传入的字符串开始或结束。否则,方法返回False

python
>>> a="I'm a dog."
>>> a.startswith("I'm")
True
>>> a.startswith("you")
False
>>> a.endswith("dog.")
True
>>> a.endswith("cat.")
False

字符串连接

如果有一个字符串列表,需要将它们连接起来,成为一个单独的字符串,join()方法就很有用。join()方法在一个字符串上调用,参数是一个字符串列表,返回一个字符串。返回的字符串由传入的列表中每个字符串连接而成。

python
>>> ','.join(['dog','cat','fish'])
'dog,cat,fish'
>>> ' '.join(['dog','cat','fish'])
'dog cat fish'

字符串分割

split()方法针对一个字符串调用,返回一个字符串列表。

python
>>> "I'm a dog".split()
["I'm", 'a', 'dog']

对齐文本

rjust()ljust()字符串方法返回调用它们的字符串的填充版本,通过插入空格来对齐文本。这两个方法的第一个参数是一个整数长度,用于对齐字符串。

python
>>> 'dog'.rjust(10)
'       dog'
>>> 'dog'.ljust(10)
'dog       '

rjust()ljust()方法的第二个可选参数将指定一个填充字符,取代空格字符。

python
>>> 'dog'.rjust(10,'*')
'*******dog'

center()字符串方法与ljust()rjust()类似,但它让文本居中,而不是左对齐或右对齐。

python
>>> 'dog'.center(20,'=')
'========dog========='

删除空白字符

strip()字符串方法将返回一个新的字符串,它的开头或末尾都没有空白字符。lstrip()rstrip()方法将相应删除左边或右边的空白字符。

python
>>> a = ' Hello World '
>>> a.strip()
'Hello World'
>>> a.lstrip()
'Hello World '
>>> a.rstrip()
' Hello World'

替换字符串

replace()方法把字符串中的old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过max 次。

语法格式如下:

python
str.replace(old, new[, max])

例如:

python
>>> text = 'ok!ok!are you ok?'
>>> text.replace('ok!','no!')
'no!no!are you ok?'

字符串格式化

字符串格式化目前有三种方式,分别为占位符(%)、formatf-string

f-string

在Python3.6中,引入了一种新的格式化字符串的方法:f-string。相比占位符和formatf-string更加方便简单。

f-string是指以Ff为前缀的字符串。例如:

python
>>> length = 30
>>> width = 15
>>> f'矩形的长为{length}cm,宽为{width}cm,面积为{length*width}'
'矩形的长为30cm,宽为15从cm,面积为450'
>>> F'矩形的长为{length}cm,宽为{width}cm,面积为{length*width}'
'矩形的长为30cm,宽为15从cm,面积为450'

3.8版本又引入一个=符号,例如:

python
>>> f'矩形{length=}cm,{width=}cm,面积为{length*width}'
'矩形length=30cm,width=15cm,面积为450'

常见问题解决方案

使用多个界定符分割字符串

问题

你需要将一个字符串分割为多个字段,但是分隔符(还有周围的空格)并不是固定的。

解决方案

string 对象的 split() 方法只适应于非常简单的字符串分割情形, 它并不允许有多个分隔符或者是分隔符周围不确定的空格。 当你需要更加灵活的切割字符串的时候,最好使用 re.split() 方法:

python
>>> line = 'asfaf dg;gdg,ddggd,hfhh;gddd gg'
>>> import re
>>> re.split(r'[;,\s]\s*',line)
['asfaf', 'dg', 'gdg', 'ddggd', 'hfhh', 'gddd', 'gg']

知识点补充:re.split()方法

语法格式:

python
import re


# maxsplit是分离的次数,maxsplit=1分离一次,默认为0,不限制次数。
re.split(pattern, string, maxsplit=0)

__EOF__


  • 本文作者: 罗恩
  • 本文链接: https://www.cnblogs.com/Rohn/p/13176889.htm
    l

    
    相关教程