Python字符串使用方法

Python字符串

有编程基础的人对字符串并不陌生,在C++中定义一个字符需要带上数据类型如:

string str=“Hello”

而在Python中定义一个字符串很方便

str = ‘Hello’  #使用单引号

str = “Hello” #使用双引号

Python字符串使用方法:

capitalize()方法,将字符串首字母大写

str='hello word!'
test = str.capitalize()
print(test)
输出:

Hello word!

2 casefold()方法,将字符串转换为小写

str='HELLO word!'
test = str.casefold()
print(test)
输出:hello word!

3 center(self, width, fillchar=None)方法,使用fillchar填充到原字符串的两端,直至长度为width

str='HELLO word!'
test = str.center(12,'a')
print(test)
输出:HELLO word!a

str='HELLO word!'
test = str.center(13,'a')
print(test)
输出:aHELLO word!a

4 count(self, sub, start=None, end=None)方法,统计sub在字符串中出现的次数,可以指定起始位置与结束位置

str='abbcccddddeeeee'
test = str.count('c')
print(test)
输出:3

str='abbcccddddeeeee'
test = str.count('c',0,4)
print(test)
输出:1

str='abbcccddddeeeee'
test = str.count('ee')
print(test)
输出:2

5 encode(encoding='UTF-8',errors='strict')方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。

endswith(self, suffix, start=None, end=None)方法,判断字符串是否以suffix结尾,可以指定起始位置与结束位置

str='abbcccddddeeeee'
test = str.endswith('e')
print(test)

输出:TRUE
str='abbcccddddeeeee'
test = str.endswith('e',0,6)
print(test)
输出:FALSE
str='abbcccddddeeeee'
test = str.endswith('eee')
print(test)
输出:TRUE
7 expandtabs(self, tabsize=8)方法,将\t转换为空格,可指定大小,默认为8
str='abbccc\tddddeeeee'
test = str.expandtabs(16)
print(test)
输出:abbccc          ddddeeeee
str='abbccc\tddddeeeee'
test = str.expandtabs()
print(test)
输出:abbccc  ddddeeeee
8 find(self, sub, start=None, end=None)方法,查找字符串sub第一次出现的位置,若没有返回-1
str='abbcccddddeeeee'
test = str.find('dd')
print(test)
输出:6
str='abbcccddddeeeee'
test = str.find('f')
print(test)
输出:-1
9 format(self, *args, **kwargs)方法,格式化输出字符串。Python中是这样说明这个函数的
S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}').
直译过来就是返回一个使用参数与kwargs替换后格式化的S,替换被{{}}中的。(英语水平有限,翻译个大概,各位大神可自行翻译)
  • 直接替换
str='{0},{1}'
test = str.format('aa','bb')
print(test)
print(str)
输出:aa,bb
   {0},{1}
  • 指定替换
str='{Name},{age}'
test = str.format(Name='Li',age='18')
print(test)
print(str)
输出:Li,18
     {Name},{age}
  • 使用列表替换
list = ['a','b',]
list1 = ['c','d',]
str='{0[0]},{1[1]}'
test = str.format(list,list1)
print(test)
输出:a,d
此测试程序,使用的两个列表替换str中的值,并使用了数组下标的方式{0[0]}取的是list列表中的第一个元素,{1[1]}取的是列表list1中第二个元素故输出a,b
  • 格式限定
^、<、>分别是居中、左对齐、右对齐,后面带宽度,示例如下:
center='{:1^6}'
test = center.format('abc')
print(test)
left='{:2>6}'
test = left.format('abc')
print(test)
right='{:3<6}'
test = right.format('abc')
print(test)
输出:
1abc11
222abc
abc333
  • 精度与其他类型
b、d、o、x分别是二进制、十进制、八进制、十六进制,示例如下:
str='{:.3f}'
test = str.format(3.1415926)
print(test)
test = '{:b}'.format(20)
print(test)
test = '{:o}'.format(20)
print(test)
test = '{:d}'.format(20)
print(test)
test = '{:x}'.format(20)
print(test)
输出:
3.142 #不仅保存了后三位还进行了四舍五入
10100 #二进制
24 #八进制
20 #十进制
14 #16进制
  • 使用‘,’号作为数字的分割
test = '{:,}'.format(2147483647)
print(test)
输出:
2,147,483,647
10 isalpha(self)方法,判断字符串中的字符是否为同一类型,Bool类型
str='adc'
test = str.isalpha()
print(test)
str1='123adc'
test = str1.isalpha()
print(test)
输出:
True
False
11 isdigit(self)方法,判断一个字符串中的元素是否均为数字,Bool类型
str='adc'
test = str.isdigit()
print(test)
str1='1234567890'
test = str1.isdigit()
print(test)
输出:
False
True
12 islower(self)方法,判断字符串是否均为小写是输出True,否输出False
str='adc'
test = str.islower()
print(test)
str1='ABcd'
test = str1.islower()
print(test)
输出:
True
False
13 isspace(self)方法,判断字符串是否为空格是输出True否输出False
str='   '
test = str.isspace()
print(test)
str1='  AB   cd  '
test = str1.isspace()
print(test)
输出:
True
False
14 istitle(self)方法,判断所有单词的首字母是否为大写是输出True否输出False
str='Hello Word'
test = str.istitle()
print(test)
str1='Hello word!'
test = str1.istitle()
print(test)
输出:
True
False
15 isupper(self)方法,判断字符串是否均为大写
str='HELLO WORD'
test = str.isupper()
print(test)
str1='Hello WORD'
test = str1.isupper()
print(test)
输出:
True
False
16 join(self, iterable)方法,返回一个连接的字符串
str='*'
test = str.join('hello')
print(test)
输出:h*e*l*l*o
17 def ljust(self, width, fillchar=' ')方法,左对齐字符并使用fillchar填充至width
str='HELLO'
test = str.ljust(10,'a')
print(test)
输出:
HELLOaaaaa
18 lower(self)方法,返回一个小写的字符串
str='HELLO'
test = str.lower()
print(test)
输出:
hello
19 lstrip(self, chars=None)方法,返回一个从字符串左侧开始移除chars的字符串
str='HELLO'
test = str.lstrip('H')
print(test)
输出:
ELLO
20 partition(self, sep)方法,以sep分割字符串并返回一个包含三个元素的元组
str='hello word'
test = str.partition('o')
print(test)
输出:
('hell', 'o', ' word')
21 replace(self, old, new, count=-1)方法,使用新的字符串替换旧的字符串默认全部替换,可指定次数
str='hellowordosdsossdo'
test = str.replace('o','TEST',2)
print(test)
输出:
hellTESTwTESTrdosdsossdo
22 rfind(self, sub, start=None, end=None)方法,返回sub在字符串中最后出现的索引为找到返回-1,可指定起始与结束位置
str='hello'
test = str.rfind('o')
print(test)
输出:
4
str='hello'
test = str.rfind('o',0,3)
print(test)
输出:
-1
23 rindex(self, sub, start=None, end=None)方法,与rfind方法类似,未找到会报ValueErro
str='hello'
test = str.rindex('x')
print(test)
输出:
ValueError: substring not found
24 rjust(self, width, fillchar=' ')方法,右对齐字符并使用fillchar填充至width
str='hello'
test = str.rjust(8,'T')
print(test)
输出:
TTThello
25 rpartition(self, sep)方法,以最后一个sep分割字符串并返回一个包含三个元素的元组
str='hello'
test = str.rpartition('l')
print(test)
输出:
('hel', 'l', 'o')
26 rsplit(self, sep=None, maxsplit=-1)方法,返回一个以sep分片的列表默认是全部分片
str='h-e-l-l-o'
test = str.rsplit('-')
print(test)
输出:
['h', 'e', 'l', 'l', 'o']
str='h-e-l-l-o'
test = str.rsplit('-',2)
print(test)
输出:
['h-e-l', 'l', 'o']
27 rstrip(self, chars=None)方法,删除 string 字符串末尾的指定字符(默认为空格)
str='h-e-l-l-o'
test = str.rstrip('o')
print(test)
输出:
h-e-l-l-
28 split(self, sep=None, maxsplit=-1)方法,返回一个以sep分片的列表
str='h-e-l-l-o'
test = str.split('-')
print(test)
输出:
['h', 'e', 'l', 'l', 'o']
str='h-e-l-l-o'
test = str.split('-',3)
print(test)
输出:
['h', 'e', 'l', 'l-o']
29 splitlines(self, keepends=False)方法,返回一个以行为单位的列表默认不包含换行标识
str='hello\nword'
test = str.splitlines()
print(test)
输出:
['hello', 'word']
str='hello\nword'
test = str.splitlines(True)
print(test)
输出:
['hello\n', 'word']
30 startswith(self, prefix, start=None, end=None)方法,若该字符串以prefix开头返回True否则返回False,可以指定开始和结束位置
str='helloword'
test = str.startswith('he')
print(test)
输出:
True
str='helloword'
test = str.startswith('hel',0,1)
print(test)
输出:
False
31 strip(self, chars=None)方法,删除字符串首尾两端的chars默认为空格
str='    helloword    '
test = str.strip()
print(test)
输出:
helloword
str='----helloword----'
test = str.strip('-')
print(test)
输出:
helloword
32 swapcase(self)方法,将字符串进行大小写转换
str='helloword'
test = str.swapcase()
print(test)
print(test.swapcase())
输出:
HELLOWORD
helloword
33 title(self)将所有单词的首字母大写
str='hello word'
test = str.title()
print(test)
输出:
Hello Word
34 upper(self)方法,将所有单词大写
str='hello word'
test = str.upper()
print(test)
输出:
HELLO WORD
35 zfill(self, width)返回width长度的字符串,左侧以0填充
str='hello'
test = str.zfill(10)
print(test)
输出:
00000hello
耗时三天(每天晚上回来写点)写完了Python中字符串的用法,第一次写博客,受到一位老师的启发万事开头难,坚持!希望能给大家带来帮助。


发布了27 篇原创文章 · 获赞 6 · 访问量 5万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章