首页 > 其他 > 详细

字符串操作

时间:2016-04-07 10:55:00      阅读:162      评论:0      收藏:0      [点我收藏+]

字符串的格式化:

str1 = "version"

num = 1.0

format = "%s" % str1

print(format)

format = "%s %d" % (str1, num)

print(format)

print(‘float : %f‘ % 1.25)

print(‘float : %.1f‘ % 1.25)

print(‘float : %.2f‘ % 1.25)

print("%(version)s : %(num).1f" % {"version":"version", "num":2})

word = "version3.0"

print(word.center(20))

print(word.center(20, "*"))

print(word.ljust(20))

print(word.rjust(20))

print("%30s" % word)



字符串转义符:

path = "hello\tworld\n"

print(path)

print(len(path))

path = r"hello\tworld\n"

print(path)

print(len(path))

word = "\thello world\n"

print(word)

print("strip():", word.strip())

print("lstrip():", word.lstrip())

print("rstrip():", word.rstrip())


字符串合并:

strs = [‘hello ‘, ‘world ‘,‘hello ‘,‘China‘]

result = "".join(strs)

print(result)


字符串截取:

sentence = "Bob said: 1, 2, 3, 4"

print(sentence.split())

print(sentence.split(","))

print(sentence.split(",", 2))


字符串比较:

str1 = 1

str2 = ‘1‘

if str1 == str2:

    print(‘same‘)

else:

    print(‘det‘)

    

if str(str1) == str2:

    print(‘same‘)

else:

    print(‘det‘)


word = "hello world"

print("hello" == word[0:5])

print(word.startswith("hello"))

print(word.endswith("ld", 6))

print(word.endswith("ld", 6, 10))

print(word.endswith("ld", 6, len(word)))


字符串反转:

word = "hello world"

li = list(word)

li.reverse()

s = "".join(li)

print(s)

dlrow olleh


字符串查找:

sentence = "This is a apple."

print(sentence.find("a"))

sentence = "This is a apple."

print(sentence.rfind("a"))


字符串替换:

centence = "hello world, hello China"

print(centence.replace("hello","hi"))

print(centence.replace("hello","hi",1))

print(centence.replace("abc","hi"))





本文出自 “大荒芜经” 博客,请务必保留此出处http://2892931976.blog.51cto.com/5396534/1761161

字符串操作

原文:http://2892931976.blog.51cto.com/5396534/1761161

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!