Python入门篇之字符串
所有标准的序列操作对字符串都适用,但字符串是不可变的
字符串常量:
单引号:‘spa"m'
双引号:"spa'm"
三引号:'''...spam...''',"""...spam..."""
转义字符:"s\tp\na\om"
Raw字符串:r"C:\new\test.spm"
Unicode字符串:u'eggs\u0020spam
单双引号是一样的
单双引号可以互换,字符常量表达式可以用两个单引号或两个双引号来表示--两种形式同样有效返回相同类型的对象:
>>> 'zxcvbn',"zxcvbn"
('zxcvbn', 'zxcvbn')
>>> #不适用转义字符就可以实现在一个字符串中包含其余种类 的引号
>>> 'knight"s',"knight's"
('knight"s', "knight's")
可以自动在任意的表达式中合并相邻的字符串常量,尽管也可以使用+操作符实现:
>>> title="sdfsd"'dfg'"fgfd"
>>> title
'sdfsddfgfgfd'
字符串的格式化使用字符%来实现:
在%的左侧放置一个字符串,右侧放置希望格式化的值,可以使用一个值,也可以使用多个值的元组或字典
>>> format="Hello. %s. %s enough for ya?"
>>> values=('world','Hot')
>>> print format % values
Hello. world. Hot enough for ya?
如果需要转换的元组作为转换表达式的一部分存在,那么必须将它用圆括号括起来,以免出错
长字符串、原始字符串
1、长字符串
如果需要写一个非常长的字符串,需要跨多行,则可以使用三个引号代替普通引号
>>> print '''this is
a
very long
string'''
this is
a
very long
string
如果一行之中最后一个字符是反斜线,那么换行符本身就“转义”了,也就是被忽略了
>>> print "hello.\
world!"
hello.world!
>>> #这个用法也适用表达式和语句
>>> 1+2+\
4+5
12
>>> print \
'hello.world'
hello.world
2、原始字符串
原始字符串以r开头,可以在原始字符串中放入任何字符,最后输出的字符串包含了转义所用的反斜线,但是不能在字符串结尾输入反斜线:
>>> print \
'hello.world'
hello.world
>>> print r'Let\'s go!'
Let\'s go!
>>> print r'this is illegal\'
SyntaxError: EOL while scanning string literal
索引与分片
字符串的字符是通过索引来提取的,将获得在特定位置的一个字符的字符串。
Python偏移量是从0开始的,并比字符串的长度小1,还支持类似在字符串中使用负偏移这样的方法从序列中获取元素,负偏移认作是从结束处反向计数
当使用一对冒号分隔的偏移索引字符串这样的序列对象时,将获取从下边界直到但不包括上边界的所有元素
索引(s[i])获取特定偏移的元素:
第一个元素的偏移为0
负偏移索引意味着从最后或右边反向进行计数
s[0]获取第一个元素
s[-2]获取了倒数第二个元素
分片(s[i:j])提取对应的部分作为一个序列:
上边界并不包含在内
分片的边界默认为0和序列的长度,如果没有给出的话
s[1:3]获取从偏移为1的元素,直到但不包括偏移为3的元素
s[1:]获取了从偏移为1直到末尾之间的元素
s[:3]获取了从偏移为0直到但是不包括偏移为3之间的元素
s[:-1]获取了从偏移为0直到但是不包括最后一个元素之间的元素
s[:]获取了从偏移0到末尾之间的元素
>>> s='spam'
>>> s[0],s[-2]
('s', 'a')
>>> s[1:3],s[1:],s[:-1]
('pa', 'pam', 'spa')
>>> s[0],s[-2]
('s', 'a')
扩展分片:第三个限制值
分片表达式增加了一个可选的第三个索引,用作步进X[I:J:K]表示:索引X对象中的元素,从偏移为I直到偏移为J-1,每隔K元素索引一次
>>> s='abcdefghijklmnop'
>>> s[1:10:2]
'bdfhj'
>>> s[::2]
'acegikmo'
>>> s='hello'
>>> s[::-1]
'olleh'
>>> s[4:1:-1]
'oll'
字符串转换工具
>>> '42'+1
Traceback (most recent call last):
File "
'42'+1
TypeError: cannot concatenate 'str' and 'int' objects
>>> int('42'),str(42)
(42, '42')
>>> repr(42),'42'
('42', '42')
>>> s='42'
>>> i=1
>>> s+i
Traceback (most recent call last):
File "
s+i
TypeError: cannot concatenate 'str' and 'int' objects
>>> int(s)+i
43
>>> s+str(i)
'421'
>>> #类似也可以把浮点数转换成字符串或把字符串转换成浮点数
>>> str(3.1415),float("1.3")
('3.1415', 1.3)
>>> text='1.23E-10'
>>> float(text)
1.23e-10
字符串代码转换
单个字符也可以通过将其传给内置的ord函数转换为其对应的ASCII码,chr函数则执行相反的操作:
>>> ord('s')
115
>>> chr(115)
's'
字符串方法
字符串比列表的方法还要丰富很多,因为字符串从string模块中“继承”了很多方法,本篇文章只介绍一些特别有用的字符串方法
1、find
find方法可以在一个较长的字符串中查找一个子字符串,它返回子串所在位置的最左端索引,如果没有找到则返回-1
>>> 'with a moo-moo here, and a moo-moo there'.find('moo')
7
>>> title="Monty Python's Flying Cirus"
>>> title.find('Monty')
0
>>> title.find('Python')
6
>>> title.find('Zirquss')
-1
这个方法可以接受可选的起始点和结束点参数:
>>> subject='$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$',1)
20
>>> subject.find('!!!')
16
>>> subject.find('!!!',0,16)
-1
2、join
join方法是非常重要的字符串方法,它是split方法的逆方法,用来在队列中添加元素:
>>> seq=[1,2,3,4,5]
>>> sep='+'
>>> sep.join(seq)
Traceback (most recent call last):
File "
sep.join(seq)
TypeError: sequence item 0: expected string, int found
>>> seq=['1','2','3','4','5']
>>> sep.join(seq)
'1+2+3+4+5'
>>> dirs='','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print 'C:'+'\\'.join(dirs)
C:\usr\bin\env
3、lower
lower方法返回字符串的小写字母版
>>> 'HDWUD HDJHS LKJDS'.lower()
'hdwud hdjhs lkjds'
4、replace
replace方法返回某字符串的所有匹配项均被替换后得到字符串
>>> 'This is a test'.replace('is','eez')
'Theez eez a test'
5、split
它是join的逆方法,用来将字符串分割成序列
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> 'C:\usr\bin\env'.split('/')
['C:\\usr\x08in\\env']
>>> 'Using the default'.split()
['Using', 'the', 'default']
注意:如果不提供任何分隔符,程序会把所有的空格作为分隔符
6、strip
strip方法返回去除两侧(不包含内部)空格的字符串:
>>> ' internal whitespace is kept '.strip()
'internal whitespace is kept'
也可指定需要去除的字符,将它们列为参数即可:
>>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
'SPAM * for * everyone'
注意:只会去除两侧的字符
7、translate
translate方法和replace方法一样,可以替换字符串中的某些部分,但是和前者不同的是,translate方法只处理单个字符

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
