python(分隔符)

split用法

split(sep,num)
1、sep:分隔符,不写默认是空格,\n,\t分隔字符串;

string="abc abc\ndef\t"
print(string.split())
#输出['abc','abc','def']

2、num:分隔次数,有sep时按sep的值分隔;

string1="sdwgfeahuidafhaiufaa"
print(string1.split("a",1))
#输出['adwgfe','huidafhaiufaa']

分隔符在字符串第一个位置或者最后一个位置时

(不写sep没有影响)

string2="124565145621"
print(string2.split("1"))
#输出['','24565','4562','']
string3="\nabc abc\ndef\t"
print(string3.split())
#输出['abc','abc','def']

当分隔符连续出现多次时

(字符串中间的n分隔符会产生n-1个空串,只有在头尾会产生n个)

string4="aaabcaadfeaaabc"
print(string4.split("a"))
#输出['', '', '', 'bc', '', 'dfe', '', '', 'bc']

多次分隔

message = 'https://mp.csdn.net/'
print(message.split("//")[1].split("/")[0].split("."))
#输出['mp', 'csdn', 'net']

strip用法

用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列

str.strip([chars])
str = "00000003210Runoob01230000000"; 
print str.strip( '0' );  # 去除首尾字符 0
 

str2 = "   Runoob      ";   # 去除首尾空格
print str2.strip();

#3210Runoob0123
#Runoob

lstrip用法

方法用于截掉字符串左边的空格或指定字符。

str.lstrip([chars])
str = "     this is string example....wow!!!     ";
print str.lstrip();
str = "88888888this is string example....wow!!!8888888";
print str.lstrip('8');

#this is string example....wow!!!
#this is string example....wow!!!8888888

replace用法

eplace() 方法把字符串中所有的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

str.replace(old, new[, max])
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);

#thwas was string example....wow!!! thwas was really string
#thwas was string example....wow!!! thwas is really string

join用法

join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

str.join(sequence)

sequence – 要连接的元素序列。

s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print (s1.join( seq ))
print (s2.join( seq ))

#r-u-n-o-o-b
#runoob

partition

partition() 方法用来根据指定的分隔符将字符串进行分割。
如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

str.partition(str)
str = "www.runoob.com"
 
print str.partition(".")
#('www', '.', 'runoob.com')

只找第一个分隔符

  • 4
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值