Python中关于字符串你应该知道这些...

Python中字符串的常见用法

定义:带有双引号/单引号/三引号

双引号:适用于所写的字符串里没有双引号的。例如:

"凡是“辛苦”必是礼物"报错​

单引号:适用于所写的字符串里没有单引号的。例如:

'I'm xiaoming'报错​​

三引号:适用于多行字符串。例如:

''' 灯火星星...人声杳杳...歌不尽乱世烽火'''.上述三行可正常输出​​​​

字符串可以用"" "" "" 、"str1 str2 str3"和("" "" "")以及("str1 str2 str3")表示而("","","")和 "","",""是元组

>>> name = "Jerry","Jenny"
>>> type(name)
<class 'tuple'
>>>> name = ("as" "we" "can" "do")
>>> type(name)
<class 'str'
>>>> poems = ("曾经沧海难为水","除去巫山不是云")​
>>> type(poems)
<class 'tuple'
>​>>> name = "Jack","Keoa","Kim"
>>> name('Jack', 'Keoa', 'Kim')
>>> type(name)
<class 'tuple'
>>>> name = ("as" "we" "can" "do")
>>> type(name)
<class 'str'
>>>> name = "Jerry Jenny"
>>> name
'Jerry Jenny'
>>> type(name)
<class 'str'>​>>> 
name = ("Jerry Jack Tom")
>>> name
'Jerry Jack Tom'
>>> type(name)
<class 'str'>

一些性质

\t \n \t\n​

\t: \t表示空四个字符,也称缩进,相当于按一下Tab键
>>> name = "\tJerry Jenny"
>>> print(name)        
     Jerry Jenny
>>> name = "Jerry\tJenny"
>>> print(name)
Jerry   Jenny
>>> name = "Jer\try Jen\tny"
>>> print(name)
Jer     ry Jen  ny
\n : \n表示换行,相当于按一下回车
>>> name = "Jerry Jenny\n"
>>> print(name)
Jerry Jenny

>>> name = "Jerry\nJenny"
>>> print(name)
Jerry
Jenny
>>> name = "Jerry\nJenn\ny"
>>> print(name)
Jerry
Jenny​

\t\n: \n\t表示换行加每行空四格
>>> name = "\tJerry Jenny\n"
>>> print(name)
        Jerry Jenny

>>> name = "\tJerry\nJenny"
>>> print(name)
        Jerry
Jenny
>>> name = "\t\nJjerry Jenny"
>>> print(name)

Jjerry Jenny
>>> name = "Jerry Jenny\t\n"
>>> print(name)
Jerry Jenny

.center(number," ")以number个居中对齐
>>> name = "Jerry Tom"
>>> name.center(50)
'                    Jerry Tom                     '
>>> name.center(50,"-")
'--------------------Jerry Tom---------------------'​
.count(" ",start,end) 找指定字符串在star到end范围内出现的次数
>>> name = "Jenny Jerry"
>>> name.count("J")
2
>>> name.count("J",1,7)    #   一个空格占一个下标
1
>>> name.count("J",1,6)    #  顾头不顾尾
0
>>> name[6]
'J'
>>> name.count("nn")
1​
.endswith("") 检查字符串最后是不是以指定字符结尾的
>>> name = "Jenny Jerry"
>>> name.endwith("rry")    # 是.endswith而不是endwith哦
Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'str' object has no attribute 'endwith'
>>> name = "Jenny Jerry"
>>> name.endswith("rry")
True
>>> name.endswith(3)   #  不支持整型
Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: endswith first arg must be str or a tuple of str, not int
>>> name.endswith("3")
False
>>> name.endswith("y Jerry")
True
.startswith("") 检查字符串湿奴是以指定字符开头的
>>> name = "Jenny Jerry"
>>> name.startswith("Je")
True
>>> name.startswith("e")
False​
.find("",start,end),同样是顾头不顾尾,在字符串内存在指定字符则返回第一个出现的下标,不存在则返回-1
>>> name = "Jerry Jenny"
>>> name.find("J")
0
>>> name.find("J",1)
6
>>> name.find("J",1,7)
6
>>> name.find("J",1,6)
-1                                  #  顾头不顾尾检索不到6,故不存在返回-1
>>> name.find("m")
-1​
.format() 格式化打印
>>> a = "my name is %s,i am %s years old"  %("Jerry",20) 
>>> a
'my name is Jerry,i am 20 years old'
>>> a = "my name is %s,i am %d years old"  %("Jerry",20)
>>> a'
my name is Jerry,i am 20 years old'
>>> a = "my name is {0},i am {1} years old"
>>> a.format("Jerry",20) # 直接打印出来不用再调用a或者print
'my name is Jerry,i am 20 years old'
>>> a = "my name is {name},i am {age} years old"
>>> a.format(name ="Jerry",age=20)'
my name is Jerry,i am 20 years old'
>>> a = "she is {name},{name} is {age} years old"
>>> a.format(name="Jerry",age=20)
'she is Jerry,Jerry is 20 years old'
.isdigit() 判断是不是整数
>>> name = "Jerry"
>>> name.isdigit()
False
>>> age = "12"
>>> age.isdigit()
True
>>> a = "Jerry,20"
>>> a.isdigit()
False​​
>>> b="12"
>>> b.isdigit()
True
>>> b = "20"+"2"
>>> b
'202'
>>> b.isdigit()
True
>>> b = "20 12"
>>> b.isdigit()
False
>>> "20".isdigit()
True
>>> "20 1".isdigit()
False
>>> a = "20 1"
>>> a
'20 1'​
>>> a = 21
>>> a.isdigit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'isdigit'
.capitalize() 首字母大写
>>> name = "jerry amy"
>>> name.capitalize()
'Jerry amy'
>>> name = "Jerry amy"
>>> name.capitalize()
'Jerry amy'​
.index("",start,end) 索引找出指定元素的第一个下标
>>> name = "Jerry"
>>> name.index("J")
0
>>> name.index("r")
2
>>> name.index("r",3,4)
3​
.casefold() 大写全部变为小写
>>> name = "Jerry Tom"
>>> name'Jerry Tom'
>>> name.casefold()
'jerry tom'
.lower()全部变小写
>>> name ="Jerry Jenny"
>>> name.lower()
'jerry jenny'
>>> name = "jerry jenny"
>>> name.lower()
'jerry jenny'
.upper()全部变大写
>>> name = "Jenny Jerry"
>>> name.upper()
'JENNY JERRY'
>>> name = "Jenny-Jerry"
>>> name.upper()
'JENNY-JERRY'
.islower()判断出现字符的地方是不是全都是小写,如果没有字符,比如数字或特殊形式也返回False
>>> name ="Jerry Jenny"
>>> name.islower()
False
>>> name = "jerry jenny"
>>> name.islower()
True
>>> name = "13 jerry"
>>> name.islower()
True
>>> age = "20 12"
>>> age.islower()
False
>>> sign = "* & $"
>>> sign.islower()
False​
.isupper()判断出现字符的地方是不是全都是大写,如果没有字符,比如数字或特殊形式也返回False
>>> name = "Jerry Jenny"
>>> name.isupper()
False
>>> name = "JERRY JENNY"
>>> name.isupper()
True
>>> name = "12"
>>> name.isupper()
False
>>> name = "JERRY 12"
>>> name.isupper()
True
>>> name = "JENNY 12t"
>>> name.isupper()
False
>>> poems = "曾经沧海难为水,除去巫山不是云"
>>> name.isupper()
False​​
>>> poems = "曾经沧海难为水,除去巫山不是云A"
>>> poems.isupper()
True
>>> poems = "曾经沧海难为水,除去巫山不是云,A"
>>> poems.isupper()
True
.swapcase()把字符串里的大写变小写,小写变大写
>>> name = "Jenny Jerry"
>>> name.swapcase()
'jENNY jERRY'
>>> poems = "曾经沧海难为水,除去巫山不是云"
>>> poems.swapcase()
'曾经沧海难为水,除去巫山不是云'
.isspace()判断有没有空间
>>> a =''
>>> a.isspace() # 仅有引号不算 必须只有空格
False
>>> a = ' '
>>> a.isspace()
True
>>> a = '   '
>>> a.isspace()
True​>
>> a = '1  2     3'
>>> a
'1  2     3'
>>> a.isspace()
False
"".join()把列表或者字符串里面的字符以“”里面的形式拼接起来
>>> numbers = [1,2,4]
>>> "-".join(numbers)
Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: sequence item 0: expected str instance, int found
>>> str = ["1","2","4"]
>>> "-".join(str)'
1-2-4'
>>> name = ("Jerry" "Jenny" "Alex")
>>> "*".join(name)
'J*e*r*r*y*J*e*n*n*y*A*l*e*x'
>>> "-".join(name)
'J-e-r-r-y-J-e-n-n-y-A-l-e-x'
>>> "".join(name)'
JerryJennyAlex'
>>> name = ("Jerry","Jenny","Alex")
>>> "-".join(name)
'Jerry-Jenny-Alex'
.ljust(step,"sign") 从左对齐step个不够的用sign补齐
>>> poems = ("曾经沧海难为水" "除去巫山不是云")
>>> (poems).ljust(50,"_")
'曾经沧海难为水除去巫山不是云____________________________________'
>>> poems.ljust(50,"-")
'曾经沧海难为水除去巫山不是云------------------------------------'
.rjust(step,"sign")从右对齐step个不够的用sign补齐
>>> poems.rjust(50,"*")
'************************************曾经沧海难为水除去巫山不是云'​>>> poems.rjust(50,"")
Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: The fill character must be exactly one character long
>>> poems.rjust(50," ")
'                                    曾经沧海难为水除去巫山不是云'​
.zfill(step)从左对齐step个不够的用0补齐
>>> poems = "曾经沧海难为水,除去巫山不是云"
>>> poems.zfill(50)
'00000000000000000000000000000000000曾经沧海难为水,除去巫山不是云'
.strip() 清楚两边格式 即将字符串里两边的换行缩进都清除 如果在中间就清除不了
>>> name = "Jerry Jenny\t\n"
>>> print(name)
Jerry Jenny

>>> name.strip()
'Jerry Jenny'
>>> name = "Jenny\tJerry\n"
>>> print(name)
Jenny    Jerry

>>> name.strip()
'Jenny\tJerry'
>>> name = "         Jerry-Jenny \t Jack\n"
>>> print(name)
         Jerry-Jenny     Jack

>>> name.strip()
'Jerry-Jenny \t Jack'
>>> name = "------------- Jerry\nJenny      "
>>> print(name)
------------- JerryJenny    
>>> name.strip()
'------------- Jerry\nJenny'
.lstrip() 清楚左边格式 即将字符串左边的换行缩进都清除 如果在中间和右边就清除不了
>>> name = "\t\nJjerry Jenny"
>>> print(name)

Jjerry Jenny
>>> name.lstrip()
'Jjerry Jenny'
>>> name = "Jerry Jenny\t\n"
>>> name.lstrip()
'Jerry Jenny\t\n'
.rstrip() 清楚右边格式 即将字符串右边的换行缩进都清除 如果在中间和左边就清除不了
>>> name = "Jerry Jenny\t\n"
>>> name.rstrip()
'Jerry Jenny'
>>> name = "\t\nJjerry Jenny"
>>> name.rstrip()
'\t\nJjerry Jenny'
.replace("str1","str2",count)把字符串里的str1改count次str2
>>> a = "I am 20 years old,and Amy is 20 years old too"
>>> a.replace("20","21")
'I am 21 years old,and Amy is 21 years old too'
>>> a.replace("20","21",1)
'I am 21 years old,and Amy is 20 years old too'
.split("",count) 通过指定分隔符对字符串进行切片,count默认=-1,即全分
>>> name = "Jerry Jenny Jack"
>>> name.split()
['Jerry', 'Jenny', 'Jack'] # 默认count=-1,即全分
>>> name.split(" ",1)
['Jerry', 'Jenny Jack']
>>> name = "Jerry,Jenny,Jack"
>>> name.split()
['Jerry,Jenny,Jack']
>>> name.split(",",1) # 只分一次,从左算起
['Jerry', 'Jenny,Jack']
>>> name = "Jerry-Jenny#Jack"
>>> name
'Jerry-Jenny#Jack'
>>> name.split()
['Jerry-Jenny#Jack']
>>> name.split("-") # 依据-开始分
['Jerry', 'Jenny#Jack']
>>> name.split("#",2)
['Jerry-Jenny', 'Jack']​
.rsplit("",count)和.split()用法基本一样,只是从右开始分,count=-1时看不出来区别
>>> name = "Jerry-Jenny#Jack"
>>> name
'Jerry-Jenny#Jack'
>>> name.rsplit()
['Jerry-Jenny#Jack']
>>> name.rsplit("-")
['Jerry', 'Jenny#Jack']
>>> name.rsplit("#")
['Jerry-Jenny', 'Jack']​
>>> name = "*Jack*Jerry#Jenny"
>>> name.rsplit("*",1) # 从右开始按*分一次
['*Jack', 'Jerry#Jenny']
>>> name.rsplit("*") # 从右开始按*全分,从又开始算起相当于第一个*号前面是个空格
['', 'Jack', 'Jerry#Jenny']
>>> name.split("*",1) # 从左开始按*分一次
['', 'Jack*Jerry#Jenny']
>>> name.split("*")
['', 'Jack', 'Jerry#Jenny']

拼接:可进行字符串的加,乘,例如:

str1="一重山"
str2="两重山"
str1+str2
'一重山两重山'​​​      # 输出结果
str1*3'一重山一重山一重山'​​   # 输出结果

​####其他运算基本上都不能实现,比如减法,除法,乘方

欧克,先写到这里啦,如果有不对的地方,望指正呀~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,923评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,154评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,775评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,960评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,976评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,972评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,893评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,709评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,159评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,400评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,552评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,265评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,876评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,528评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,701评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,552评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,451评论 2 352

推荐阅读更多精彩内容