Python 字符串操作

来源:互联网 发布:计算机美工专业 编辑:程序博客网 时间:2024/05/29 14:53
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