标签:字符串
字符串的格式化:
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