亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

python基礎之字符串

標簽:
Python

组成字符串的两种方式

a = 'lao'
b = 'wang'
d = a + b
e = "===%s===" % (a+b)  #a与b必须都是字符串
print(d)
print(e)

字符串下标

name = 'abcdef'
print(name[0])
print(name[5])
print(name[len(name)-1])
print(name[-1])

字符串切片

name = 'abcdefABCDEF'
#切片语法:string[起始位置:终止位置:步长]
print(name[2:5])        #cde
print(name[2:])         #cdefABCDEF
print(name[2:-2])       #cdefABCD
print(name[2:-1:2])     #ceACE
print(name[0:])
#以下写法将字符串逆序
print(name[-1::-1])         #FEDCBAfedcba
print(name[::-1])           #前面两个都省略,关键看后面的步长

字符串函数

https://img1.sycdn.imooc.com//5b1a40a60001541609940209.jpg

#coding=utf-8
myStr = "hello world and we are the world"
print(myStr.count("world"))     #2
#统计字符串出现的次数,如果没有则返回0
print(myStr.replace("world","WORLD"))       #hello WORLD and we are the WORLD
#注意:replace不会对原字符串产生任何影响
print(myStr.replace("world","xxxxx",1))     #hello xxxxx and we are the world
#replace第一个参数为:要替换的字符串,第二个参数为:替换成什么字符串,第三个参数为:如果要替换的字符串出现多次那么要替换的个数
print(myStr.split(" "))         #['hello', 'world', 'and', 'we', 'are', 'the', 'world']
print(myStr.capitalize())       #Hello world and we are the world
file_name = "xxxxx.txt"
print(file_name.endswith(".txt"))           #True
#ljust , rjust , center
lyric = "Tonight , I feel close to you"
print(lyric.center(50))             #          Tonight , I feel close to you           
print(lyric.ljust(50))
print(lyric.rjust(50))
#lstrip , rstrip , strip
name = "  who are you "
print(name.lstrip())
print(name.rstrip())
print(name.strip())
#partition , rpatition
print(myStr.partition("world"))         #('hello ', 'world', ' and we are the world')
print(myStr.rpartition("world"))        #('hello world and we are the ', 'world', '')
#spliteline     按照换行符进行分隔
content = "hello\nworld\nxxx\nyyy"
print(content.splitlines())                     #['hello', 'world', 'xxx', 'yyy']
#isalpha            判断是否是纯字母
#isdigit            判断是否是纯数字
#isalnum         判断是否是字母与数字
#join
a = ['aaa','bbb','ccc']
b = '='
print(b.join(a))                #aaa=bbb=ccc
b = ' '
print(b.join(a))                #aaa bbb ccc

面试题:给定一个字符串str,返回使用空格或者'\t'分割后的倒数第二个子串

str = "haha nihao a \t heihei \t woshi nide \t hao \npenyou"
print(str)
sstr = str.split()
print(sstr)                 #['haha', 'nihao', 'a', 'heihei', 'woshi', 'nide', 'hao', 'penyou']
print(' '.join(sstr))

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消