• 运维特工,战胜心魔!!
  • 有些事情其实没有那么难,只是我们感觉难,走出第一步!
  • 你所浪费的今天,是昨天死去的人奢望的明天!!!
  • 欢迎访问 unixfbi.com 运维特工社区http://unixfbi.com/
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧
  • 运维特工:http://www.unixfbi.com
  • 人生没有白走的路,每一步都算数!!
  • 空杯心态,沉淀自己!

Python-字符串

Python unixfbi 11个月前 (08-15) 3309次浏览 已收录 0个评论 扫描二维码
文章目录[隐藏]

Python-字符串

一、字符串介绍

字符串是 Python 中最常见的数据类型,是不可变类型,我们可以使用单引号、双引号或者三引号来创建字符串。

如果要使用 unicode 编码,则在字符之前使用字符 u 进行标识,如 u"unixfbi.com"

支持 :
索引运算:[i]
切片运算:[i:j]
扩展切片:[i:j:stride]
max()、min(),len()等等。

创建字符串:

>>> str1 = 'hello world!'
>>> str2 = "unixfbi.com"

二、字符串常用操作

1.访问字符串值

Python 访问获取字符串的值,可以使用方括号来截取字符串。

>>> str1 = 'hello world!'
>>> str1[1]
'e'
>>> str1[1:8]
'ello wo'

2.字符串运算符

+:字符串连接

>>> str1 = 'abc'
>>> str1 = 'Pthon'
>>> str1 + str2
'Pthonunixfbi.com'

*:重复输出字符串

>>> str1 = 'Pthon'
>>> str1*5
'PthonPthonPthonPthonPthon'

in:成员运算符,如果字符串中包含指定的字符就返回 True

>>> str1 = "UnixFBI"
>>> 'F' in str1       
True
>>> 'k' in str1 
False

**not in **: 成员运算符,如果字符串中不包含给定的字符就返回 True

>>> str1 = "UnixFBI"
>>> 'F' not in str1
False
>>> 'K' not in str1
True

三、字符串内置方法

查看字符串有多少内置方法:

>>> str.
str.capitalize(    str.find(          str.isdecimal(     str.istitle(       str.mro(           str.rsplit(        str.title(
str.casefold(      str.format(        str.isdigit(       str.isupper(       str.partition(     str.rstrip(        str.translate(
str.center(        str.format_map(    str.isidentifier(  str.join(          str.replace(       str.split(         str.upper(
str.count(         str.index(         str.islower(       str.ljust(         str.rfind(         str.splitlines(    str.zfill(
str.encode(        str.isalnum(       str.isnumeric(     str.lower(         str.rindex(        str.startswith(    
str.endswith(      str.isalpha(       str.isprintable(   str.lstrip(        str.rjust(         str.strip(         
str.expandtabs(    str.isascii(       str.isspace(       str.maketrans(     str.rpartition(    str.swapcase(  

内置方法有点多,我们介绍几个常用的。

capitalize(self, /):将字符串的第一个字符转换为大写。
capitalize(self, /)
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.

>>> str1 = "unixFBI"
>>> str1.capitalize()
'Unixfbi'

startswith():检查字符串是否以指定字符开头,可以指定范围。
startswith(...)
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.

>>> str1 = "abcdefabcd"
>>> str1.startswith('a') 
True
>>> str1.startswith('a',2,5)
False

endswith(...):查看指定字符串是否以指定的字符结尾,也可以查询一个区间。
endswith(...)
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.

>>> str1.endswith('F')
False
>>> str1.endswith('i')
True
>>> str1.endswith('F',2,8)
False

find(...):检查 sub 是否包含在字符串中,如果指定范围 start 和 end,就在该范围中查找,如果包含就返回开始的索引值,否则返回-1
find(...)
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.

>>> str1 = "ABCabcABCabc"
>>> str1.find('A')
0
>>> str1.find('a')
3
>>> str1.find('A',3,len(str1))
6
>>> len(str1)
12
>>> str1.find('c',3,6)       
5
>>> str1.find('c',3,5)
-1

count():查看指定字符在字符串中出现的次数,也可以指定查询的范围,返回一个整型,没有找到返回 0
count(...)
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.

>>> str1 = "ABCabcABCabc"
>>> str1.count('A')
2
>>> str1.count('A',3,len(str1)) 
1
>>> str1.count('a',3,6)
1

index():查找指定字符在字符串中出现的位置索引,可以指定范围。如果字符串中或者指定范围不包括指定字符,就会抛出异常。
跟 find()方法一样,只不过如果 str 不在字符串中会报一个异常.
index(...)
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.

>>> str1 = "ABCabcABCabc"
>>> str1.index('A')
0
>>> str1.index('A',3,7)
6
>>> str1.index('A',3,6)   
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

isalnum():如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
isalnum(self, /)
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

>>> str1 = "ABCabcABCabc"
>>> str1.isalnum()
True
>>> str1 = "ABC*()&"     
>>> str1.isalnum()
False

isalpha(): 判断字符串是否都是字母。如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False
isalpha(self, /)
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

>>> str1 = "123"  
>>> str1.isalpha()
False
>>> str1 = "123a" 
>>> str1.isalpha()
False
>>> str1 = "abc"  
>>> str1.isalpha()
True

isdigit():判断一个字符串是不是都是数字组成。
isdigit(self, /)
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.

>>> str1 = "123"  
>>> str1.isdigit()
True
>>> str1 = "a123" 
>>> str1.isdigit()
False

isnumeric():也用来判断字符串是不是由数字组成,但是这个支持汉字数字,这是和isdigit()的区别。
True: Unicode 数字,全角数字(双字节),罗马数字,汉字数字

False: 无
isnumeric(self, /)
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.

>>> str1 = "123"  
>>> str1.isnumeric()
True
>>> str1 = "123a"   
>>> str1.isnumeric()
False
>>> str1 = "四"
>>> str1.isnumeric()
True

isspace():判断字符串是否只有空白字符组成,是返回 True,否则 False
isspace(self, /)
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

>>> str1 = "abc abc"
>>> str1.isspace()  
False
>>> str1 = "   "    
>>> str1.isspace()
True
>>> str1 = ""     
>>> str1.isspace()
False

islower():判断字符串中是否包含区分大小写的字母,如果字母全是小写就返回 Ttrue,否则返回 False
islower(self, /)
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

>>> str1 = "abc"   
>>> str1.islower()
True
>>> str1 = "Abc"  
>>> str1.islower()
False
>>> str1 = "123"  
>>> str1.islower()
False
>>> str1 = "123abc"
>>> str1.islower() 
True

isupper():判断字符串中是否包含区分大小写的字母,如果字母全是大写就返回 Ttrue,否则返回 False
isupper(self, /)
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

>>> str1 = "abc"  
>>> str1.isupper()
False
>>> str1 = "Abc"  
>>> str1.isupper()
False
>>> str1 = "ABC"  
>>> str1.isupper()
True
>>> str1 = "123"  
>>> str1.isupper()
False
>>> str1 = "123ac"
>>> str1.isupper()
False
>>> str1 = "123AC"
>>> str1.isupper()
True

join():用于将序列中的元素以指定的字符连接生成一个新的字符串。
不仅字符串也可以是列表,元组,字典都可以做这样的操作。
join(self, iterable, /)
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'

>>> s1 = "-"             
>>> list1 = ['a','b','c']
>>> s1.join(list1)       
'a-b-c'
>>> s2 = ""
>>> s2.join(list1)
'abc'
>>> s3 = " "      
>>> s3.join(list1)
'a b c'
>>> dic1 = { "key1": "value1", "key2": "value2", "key3": "value3" }
>>> s1.join(dic1)
'key1--key2--key3'

split():以字符串中指定的字符来分割字符串,可以指定分割次数,默认是-1 表示不限制次数。
split(self, /, sep=None, maxsplit=-1)
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.

>>> str1 = "abcdefabcdeabce123"
>>> str1.split('e')            
['abcd', 'fabcd', 'abc', '123']
>>> str1.split('e',2)
['abcd', 'fabcd', 'abce123']

swapcase():大小写转换,把大写转换为小写,小写转换为大写
swapcase(self, /)
Convert uppercase characters to lowercase and lowercase characters to uppercase.

>>> str1 = "abcEFG"
>>> str1.swapcase()
'ABCefg'

lower():把大写转换为小写
lower(self, /)
Return a copy of the string converted to lowercase.

>>> str1 = "abcEFG"
>>> str1.lower()
'abcefg'

replace():字符替换,count 表示替换的次数,默认是全部替换
replace(self, old, new, count=-1, /)
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.

>>> str1 = "abc123abc123abc"
>>> str1.replace('a','A')   
'Abc123Abc123Abc'
>>> 
>>> str1 = "abc123abc123abc"
>>> str1.replace('a','A',2) 
'Abc123Abc123abc'
>>> str1.replace('a','8',1)
'8bc123abc123abc'

count():查看指定字符出现的次数,可以指定范围,如果不存在该字符会返回 0
count(...)
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.

>>> str1 = "abc123abc123abc"
>>> str1.count('b')
3
>>> str1 = "abc123abc123abc"
>>> str1.count('b',1,3)     
1
>>> str1.count('b',3,7)
0
>>> str1.count('b',3,8)
1

参考文档

http://www.runoob.com/python3/python3-string.html


UnixFBI 运维特工 , 版权所有丨如未注明 , 均为原创丨 转载请务必注明原文链接http://www.unixfbi.com/561.html
喜欢 (19)
[支付宝]
分享 (0)
unixfbi
关于作者:
运维工程师一枚,做有价值的事情!
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址