码迷,mamicode.com
首页 > 编程语言 > 详细

python-字符串

时间:2019-12-29 10:53:39      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:ppi   called   first   lap   unknown   nta   nal   convert   arguments   

字符串是python的基本数据类型,支持拼接、迭代、切片等操作

在Python中,加了引号的字符都被认为是字符串!(单引号或双引号)

a = "hello"
b = "world"
print(a+b)
print(a[1:4])
for i in a:
    print(i,end="")

输出:

helloworld
ell
hello

字符串函数

字符串操作函数众多,记录主要的、常用的函数

count()

S.count():返回某个字符串中子串出现的个数,且可以指定查找的起始位置。如果找不到则返回数字0

 def count(self, sub, start=None, end=None):
     """
     S.count(sub[, start[, end]]) -> int
     
     Return the number of non-overlapping occurrences of substring sub in
     string S[start:end].  Optional arguments start and end are
     interpreted as in slice notation.
     """
     return 0
casefold()

S.casefold() :返回一个全部小写的字符串

lower()

返回小写字符串,同 casefold()

def lower(self, *args, **kwargs): # real signature unknown
 """ Return a copy of the string converted to lowercase. """
 pass
encode()

返回调用者的字节形式,需要指定编码规则

find()

查找子串是存在,可以指定查找的起始位置,找到返回第一个出现的索引值,否则返回-1

 def find(self, sub, start=None, end=None): 
     """
     S.find(sub[, start[, end]]) -> int
     
     Return the lowest index in S where substring sub is found,
     such that sub is contained within S[start:end].  Optional
     arguments start and end are interpreted as in slice notation.
     
     Return -1 on failure.
     """
     return 0
format()

formate()格式化函数:通过{} 对字符串做字面量插值,取代占位符的%s

#用法1:不指定位置,默认位置
a = "hello"
b = "world"
s = "{},{}".format(a,b)   # s= "hello,world"

#方法2,指定位置
s = "{1},{1}".format(a,b) # s= "world,world"

#方式3:指定位置
s="{1} {0} {1}".format(a,b)  # s="world hello world"

#方式4: 字典做参数
flag = {"a":a, "b":b}
s = "{a},{b}".format(**flag) # s="hello,world"

#方式5: 列表做参数
...
index()

返回字符串中子串的索引值,默认返回第一个出现的位置的索引,可以指定查找的起始位置

当要查找的子串不不存在时抛出异常

def index(self, sub, start=None, end=None): 
     """
     S.index(sub[, start[, end]]) -> int
     
     Return the lowest index in S where substring sub is found, 
     such that sub is contained within S[start:end].  Optional
     arguments start and end are interpreted as in slice notation.
     
     Raises ValueError when the substring is not found.
     """
     return 0
isalnum()

判断字符串是否是数字和字母的组合,如果是返回True,否则False

isdigit()

判断字符串是否可以转数字类型,如果是返回True,否则False。不支持浮点数的判断

islower()

判断字符串是否是小写,如果是返回True,否则False

isupper()

判断字符串是否是大写,如果是返回True,否则False

join()

拼接字符串

#方式1
a = "hello"
s= "__".join(a)
# s = "h__e__l__l__o"

#方式2
a = "hello"
b = "world"
s= "".join((a,b))
# s = "helloworld"

对于可迭代的数据类型,在元素间用指定的字符连接

def join(self, ab=None, pq=None, rs=None): 
 """
 Concatenate any number of strings.
 
 The string whose method is called is inserted in between each given string.
 The result is returned as a new string.

 Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
 """
 pass
partition()

用指定字符(串)(分隔符)把调用的字符串分割成三部分,以元组的形式返回。如果没有找到分隔符,字符串自己作为元组的第一个元素,后两个元素为空。

b = "Beijingaaaiaaaa"

print(b.partition("i"))
#output:  ('Be', 'i', 'jingaaaiaaaa')
def partition(self, *args, **kwargs): # real signature unknown
 """
  Partition the string into three parts using the given separator.

 This will search for the separator in the string.  If the separator is found,
     returns a 3-tuple containing the part before the separator, the separator
     itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string
     and two empty strings.
     """
 pass
replace()

字符串替换函数,可以指定替换的个数,默认全部替换,如果指定超出则全部替换

b = "Beijingaaaiaaaa"
s = b.replace("i", "*",)
# output: s = "Be*j*ngaaa*aaaa"

b = "Beijingaaaiaaaa"
s = b.replace("i", "*",2)
# output: s = "Be*j*ngaaaiaaaa"
def replace(self, *args, **kwargs): 
 """
 Return a copy with all occurrences of substring old replaced by new.

 count
     Maximum number of occurrences to replace.
     -1 (the default value) means replace all occurrences.

 If the optional argument count is given, only the first count occurrences are
     replaced.
     """
 pass
split()

字符串分割,按指定子串分割,且可以指定分割个数。列表形式返回。默认按空格分隔

b = "Beijingaaaiaaaa"
s= b.split("i",2)
# s = "['Be', 'j', 'ngaaaiaaaa']"
def split(self, *args, **kwargs):
 """
 Return a list of the words in the string, using sep as the delimiter string.
 
 sep
    The delimiter according which to split the string.
    None (the default value) means split according to any whitespace,
     and discard empty strings from the result.
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.
 """
 pass
strip()

默认返回一个移除头部和尾部空格的字符串,也可以指定移除的字符

def strip(self, *args, **kwargs): # real signature unknown
 """
     Return a copy of the string with leading and trailing whitespace remove.
     If chars is given and not None, remove characters in chars instead.
     """
 pass
zfill()

在数字字符串的左边填充指定位数的0,

a = "123"
s = a.zfill(10)
print(s)  # 0000000123

python-字符串

标签:ppi   called   first   lap   unknown   nta   nal   convert   arguments   

原文地址:https://www.cnblogs.com/liuxu2019/p/12114242.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!