美文网首页
python 字符串操作

python 字符串操作

作者: ayusong870 | 来源:发表于2020-04-08 21:42 被阅读0次
转义字符 打印为
' 单引号
" 双引号
\t 制表符
\n 换行符
\ 倒斜杠

spam = 'That is Alice is cat.'
spam = "That is Alice's cat."
spam = 'That is Alice's cat.'

1. 原始字符串——忽略转义字符

>>> print(r'That is Alice\'s cat.') 
That is Alice\'s cat.

2. 三重引号的多行字符串

“三重引号”之间的 所有引号、制表符或换行,都被认为是字符串的一部分。Python 的代码块缩进规则不适用于多行字符串。

>>>print('''Dear Alice,  

Eve's cat has been arrested for catnapping, cat burglary, and extortion.  

Sincerely,
 Bob''')

Dear Alice,

Eve's cat has been arrested for catnapping, cat burglary, and extortion. 
 
Sincerely, 
Bob

3. 多行注释

"""This is a test Python program.
Written by Al Sweigart al@inventwithpython.com  
This program was designed for Python 3, not Python 2. 
"""

4. 字符串切片

>>> spam = 'Hello world!' 
>>> spam[0] 
'H' 
>>> spam[4] 
'o'
 >>> spam[-1] 
'!' >>> spam[0:5] 
'Hello' 
>>> spam[:5] 
'Hello' 
>>> spam[6:] 
'world!

5. 字符串中的in和not in

>>> 'Hello' in 'Hello World' 
True 
>>> 'Hello' in 'Hello' 
True 
>>> 'HELLO' in 'Hello World' 
False 
>>> '' in 'spam' 
True 
>>> 'cats' not in 'cats and dogs' 
False 

6. upper()、lower()、isupper()、islower()

upper()转换为大写、lower()转换为小写、isupper()是否大写和 islower()是否小写
isX字符串方法。

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

7. startswith()和 endswith()

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

8. join()和 split()

code result
', '.join(['cats', 'rats', 'bats']) 'cats, rats, bats'
' '.join(['My', 'name', 'is', 'Simon']) 'My name is Simon'
'ABC'.join(['My', 'name', 'is', 'Simon']) 'MyABCnameABCisABCSimo'
'My name is Simon'.split() ['My', 'name', 'is', 'Simon']
'MyABCnameABCisABCSimon'.split('ABC') ['My', 'name', 'is', 'Simon']
'My name is Simon'.split('m') ['My na', 'e is Si', 'on']

9. rjust()、ljust()和 center()方法对齐文本

>>> 'Hello'.rjust(10) 
'      Hello' 
>>> 'Hello'.rjust(20) 
'                   Hello' 
>>> 'Hello World'.rjust(20) 
'              Hello World' 
>>> 'Hello'.ljust(10) 
'Hello      '  
>>> 'Hello'.rjust(20, '*')
'***************Hello' 
>>> 'Hello'.ljust(20, '*') 
'Hello***************'
>>> 'Hello'.center(20, '=') 
'=======Hello========'

10. strip()、rstrip()和 lstrip()删除空白字符

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

11. 用 pyperclip 模块拷贝粘贴字符串

>>> import pyperclip 
>>> pyperclip.copy('Hello world!') 
>>> pyperclip.paste() 
'Hello world!

相关文章

网友评论

      本文标题:python 字符串操作

      本文链接:https://www.haomeiwen.com/subject/otbcrhtx.html