Python 字符串操作

strip 函数是unicode 或者是str 类型的一个方法, 用来去掉转义字符。
其中还有lstrip rstrip 分别去掉左边开始的转义字符, 与最后的转义字符。
实例:


word = u"我\n是\n中国人"
print word
print word.split()

#连接字符串 使用操作符

示例如下

str1="hello"
str2="word"
str3="hello"
str4="china"

result =str1+str2+str3
result+=str4
print result

hellowordhellochina



#使用join 函数连接字符串

strs = ["hello","word","hello","china"]
result = "".join(strs)
print result

join 函数的方法是一次连接列表中的每一个元素, 最后输出结果 。

字符串的截取

   字符串的截取是实际应用中经常使用的技术,被截取的部分称之为子字符串:

   word = "world"
   print word[4]


#演示是否包含或者结尾或者开始是否有字符串的方法
word = "world"
str1 = "hello world"
print str1.startswith("hello")
print word.endswith("ld")


#python 没有提供对字符串进行翻转的函数, 也没有类似chatAt  这样的函数, 但是可以使用列表和字符串
#的索引来实现字符串的翻转, 通过range 进行循环

def reverse(s):
    out =""
    li=list(s)
    for i in range(len(li),0,-1):
        out+="".join(li[i-1])
    return out

print reverse("hello the world")

# 字符串的替换替换方法

info = "hello world , hello china"
print info.replace("hello", "hi")
print info.replace("hello", "hi", 1)


  字符串当中如果没有指定要替换的个数的话, 则全部都替换, 后面的指定了1 , 说明只是替换第一个 , 其他的不替换。




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值