字符串操做

字符串的格式化:app

str1 = "version"ide

num = 1.0orm

format = "%s" % str1ip

print(format)字符串

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

print(format)io

print('float : %f' % 1.25)form

print('float : %.1f' % 1.25)class

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

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"))

相關文章
相關標籤/搜索