Home  >  Article  >  Backend Development  >  Introduction to methods of python Str class

Introduction to methods of python Str class

高洛峰
高洛峰Original
2017-03-10 14:04:571796browse

Python Str class method introduction

#capitalize():字符串首字符大写
string = 'this is a string.'
new_str = string.capitalize()
print(new_str)
#输出:This is a string.
  
#center(width, fillchar=None):将字符串放在中间,在指定长度下,首尾以指定字符填充
string = 'this is a string.'
new_str = string.center(30,'*')
print(new_str)
#输出:******this is a string.*******
  
#count(sub, start=None, end=None):计算字符串中某字符的数量
string = 'this is a string.'
new_str = string.count('i')
print(new_str)
#输出:3
  
#decode(encoding=None, errors=None):解码
string = 'this is a string.'
new_str = string.decode()
print(new_str)
  
#encode(self, encoding=None, errors=None):编码
string = 'this is a string.'
new_str = string.encode()
print(new_str)
  
#endswith(self, suffix, start=None, end=None):判断是否以某字符结尾
string = 'this is a string.'
new_str = string.endswith('ing.')
print(new_str)
#输出:True
new_str = string.endswith('xx')
print(new_str)
#输出:False
  
#expandtabs(self, tabsize=None):返回制表符。tabsize此选项指定要替换为制表符“\t' 的字符数,默认为8
string_expandtabs = 'this\tis\ta\tstring.'
new_str = string_expandtabs.expandtabs()
print(new_str)
#输出:this    is      a       string.
  
#find(self, sub, start=None, end=None):在字符串中寻找指定字符的位置
string = 'this is a string.'
new_str = string.find('a')    #找的到的情况
print(new_str)
#输出:8
new_str = string.find('xx')    #找不到的情况返回-1
print(new_str)
#输出:-1
  
#format(*args, **kwargs):类似%s的用法,它通过{}来实现
string1 = 'My name is {0},my job is {1}.'
new_str1 = string1.format('yue','tester')
print(new_str1)
#输出:My name is yue,my job is tester.
string2 = 'My name is {name},my job is {job}.'
new_str2 = string2.format(name='yue',job='tester')
print(new_str2)
#输出:My name is yue,my job is tester.
  
#index(self, sub, start=None, end=None):;类似find
string = 'this is a string.'
new_str = string.index('a')    #找的到的情况
print(new_str)
#输出:8
new_str = string.index('xx')    #找不到的情况,程序报错
print(new_str)
#输出:程序运行报错,ValueError: substring not found
  
#isalnum(self):判断字符串中是否都是数字和字母,如果是则返回True,否则返回False
string = 'My name is yue,my age is 18.'
new_str = string.isalnum()
print(new_str)
#输出:False
string = 'haha18121314lala'
new_str = string.isalnum()
print(new_str)
#输出:True
  
#isalpha(self):判断字符串中是否都是字母,如果是则返回True,否则返回False
string = 'abcdefg'
new_str = string.isalpha()
print(new_str)
#输出:True
string = 'my name is yue'
new_str = string.isalpha()    #字母中间带空格、特殊字符都不行
print(new_str)
#输出:False
  
# isdigit(self):判断字符串中是否都是数字,如果是则返回True,否则返回False
string = '1234567890'
new_str = string.isdigit()
print(new_str)
#输出:True
string = 'haha123lala'
new_str = string.isdigit()    #中间带空格、特殊字符都不行
print(new_str)
#输出:False
  
# islower(self):判断字符串中的字母是否都是小写,如果是则返回True,否则返回False
string = 'my name is yue,my age is 18.'
new_str = string.islower()
print(new_str)
#输出:True
string = 'My name is Yue,my age is 18.'
new_str = string.islower()
print(new_str)
#输出:False
  
# isspace(self):判断字符串中是否都是空格,如果是则返回True,否则返回False
string = '      '
new_str = string.isspace()
print(new_str)
#输出:True
string = 'My name is Yue,my age is 18.'
new_str = string.isspace()
print(new_str)
#输出:False
  
# istitle(self):检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
string = 'My Name Is Yue.'
new_str = string.istitle()
print(new_str)
#输出:True
string = 'My name is Yue,my age is 18.'
new_str = string.istitle()
print(new_str)
#输出:False
  
# isupper(self):检测字符串中所有的字母是否都为大写。
string = 'MY NAME IS YUE.'
new_str = string.isupper()
print(new_str)
#输出:True
string = 'My name is Yue.'
new_str = string.isupper()
print(new_str)
#输出:False
  
# join(self, iterable):将序列中的元素以指定的字符连接生成一个新的字符串。
string = ("haha","lala","ohoh")
str = "-"
print(str.join(string))
#输出:haha-lala-ohoh
  
# ljust(self, width, fillchar=None):返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
string = "My name is yue."
print(string.ljust(18))
#输出:My name is yue.
  
# lower(self):转换字符串中所有大写字符为小写。
string = "My Name is YUE."
print(string.lower())
# 输出:my name is yue.
  
# lstrip(self, chars=None):截掉字符串左边的空格或指定字符。
string = "   My Name is YUE."
print(string.lstrip())
#输出:My Name is YUE.
string = "My Name is YUE."
print(string.lstrip('My'))
#输出: Name is YUE.
  
# partition(self, sep):根据指定的分隔符将字符串进行分割。
string = "http://www.mingyuanyun.com"
print(string.partition('://'))
#输出:('http', '://', 'www.mingyuanyun.com')
  
#replace(self, old, new, count=None):把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
string = "My name is yue."
print(string.replace("yue","ying"))
#输出:My name is ying.
  
# rfind(self, sub, start=None, end=None):返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
string = "My name is yue."
print(string.rfind('is'))
#输出:8
string = "My name is yue."
print(string.rfind('XXX'))
#输出:-1
  
# rindex(self, sub, start=None, end=None):返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。
string = "My name is yue."
print(string.rindex('is'))
#输出:8
string = "My name is yue."
print(string.rindex('XXX'))
#输出:ValueError: substring not found
  
# rjust(self, width, fillchar=None):返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。
string = "My name is yue."
print(string.rjust(18))
#输出:   My name is yue.
  
# rpartition(self, sep):根据指定的分隔符将字符串从右进行分割。
string = "http://www.mingyuanyun.com"
print(string.rpartition('.'))
#输出:('http://www.mingyuanyun', '.', 'com')
  
# split(self, sep=None, maxsplit=None):通过指定分隔符对字符串进行切片。
string = "haha lala gege"
print(string.split(' '))
#输出:['haha', 'lala', 'gege']
print(string.split(' ', 1 ))
#输出: ['haha', 'lala gege']
  
# rsplit(self, sep=None, maxsplit=None):通过指定分隔符对字符串从右进行切片。
string = "haha lala gege"
print(string.rsplit(' '))
#输出:['haha', 'lala', 'gege']
print(string.rsplit(' ', 1 ))
#输出: ['haha lala', 'gege']
  
# rstrip(self, chars=None):删除 string 字符串末尾的指定字符(默认为空格).
string = "     My name is yue.      "
print(string.rstrip())
#输出:     My name is yue.
  
# strip(self, chars=None):移除字符串头尾指定的字符(默认为空格)。
string = "        My name is yue.      "
print(string.strip())
#输出:My name is yue.
  
# splitlines(self, keepends=False):按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
str1 = 'ab c\n\nde fg\rkl\r\n'
print(str1.splitlines())
# 输出:['ab c', '', 'de fg', 'kl']
str2 = 'ab c\n\nde fg\rkl\r\n'
print(str2.splitlines(True))
# 输出:['ab c\n', '\n', 'de fg\r', 'kl\r\n']
  
# startswith(self, prefix, start=None, end=None):检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
string = "My name is yue.      "
print(string.startswith('My'))
#输出:True
string = "My name is yue."
print(string.startswith('yue'))
#输出:False
  
# swapcase(self):对字符串的大小写字母进行转换。
string = "My Name Is Yue."
print(string.swapcase())
#输出:mY nAME iS yUE.
  
# title(self):返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())。
string = "my name is yue,my age is 18."
print(string.title())
#输出:My Name Is Yue,My Age Is 18.
  
# translate(self, table, deletechars=None):根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中。
from string import maketrans
str = "aoeiu"
num = "12345"
trantab = maketrans(str, num)
string = "my name is yue"
print(string.translate(trantab))
# 输出:my n1m3 4s y53
  
# upper(self):将字符串中的小写字母转为大写字母。
string = "my name is yue,my age is 18."
print(string.upper())
#输出:MY NAME IS YUE,MY AGE IS 18.
  
# zfill(self, width):返回指定长度的字符串,原字符串右对齐,前面填充0。
string = "my name is yue."
print(string.zfill(18))
#输出:000my name is yue.


The above is the detailed content of Introduction to methods of python Str class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn