02.字符串

01.字符串常用方法

#1. find方法可以在一个较长的字符串中查找子串,他返回子串所在位置的最左端索引,如果没有找到则返回-1
a = 'abcdefghijk'
print(a.find('abc'))                                  #the result : 0
print(a.find('abc',10,100))                           #the result : 11  指定查找的起始和结束查找位置

#2. join方法是非常重要的字符串方法,他是split方法的逆方法,用来连接序列中的元素,并且需要被连接的元素都必须是字符串。
a = ['1','2','3']
print('+'.join(a))                                    #the result : 1+2+3

#3. split方法,是一个非常重要的字符串,它是join的逆方法,用来将字符串分割成序列
print('1+2+3+4'.split('+'))                          #the result : ['1', '2', '3', '4']

#4. strip 方法返回去除首位空格(不包括内部)的字符串
print("   test   test    ".strip())                  #the result :“test   test”

#5. replace方法返回某字符串所有匹配项均被替换之后得到字符串
print("This is a test".replace('is','is_test'))     #the result : This_test is_test a test

1.1 find方法

作用:find方法可以在一个较长的字符串中查找子串,他返回子串所在位置的最左端索引,如果没有找到则返回-1


a = 'abcdefghijk'
print(a.find('abc'))                         #the result : 0
print(a.find('abc',10,100))                    #the result : 11  指定查找的起始和结束查找位置

1.2 join方法

作用:join方法是非常重要的字符串方法,他是split方法的逆方法,用来连接序列中的元素,并且需要被连接的元素都必须是字符串。


a = ['1','2','3']
print('+'.join(a))                                    #the result : 1+2+3

1.3 split方法

作用:这是一个非常重要的字符串,它是join的逆方法,用来将字符串分割成序列


print('1+2+3+4'.split('+'))                            #the result : ['1', '2', '3', '4']

1.4 strip

作用:strip 方法返回去除首位空格(不包括内部)的字符串


print("   test   test    ".strip())                #the result :“test   test”

1.5 replace

作用:replace方法返回某字符串所有匹配项均被替换之后得到字符串


print("This is a test".replace('is','is_test'))     #the result : This_test is_test a test

1.6 首字母大写

>>> s = 'aBdkndfkFFD'
>>> s.capitalize()
'Abdkndfkffd'

1.7 Pinyin 模块,将汉字转换成拼音

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from xpinyin import Pinyin

while True:
    p = Pinyin()
    fullname = raw_input('name:').strip()
    fullname = fullname.decode('utf8')
    print fullname
    xin = fullname[0]
    ming = fullname[1:]
    name = ming + '.' + xin
    username = p.get_pinyin(name, '')
    print username
    print username + '@yiducloud.cn'

02.字符串格式化

2.1 使用百分号(%)字符串格式化

num = 100
print("%d to hex is %x" %(num, num))        #100 to hex is 64
print("%d to hex is %#x" %(num, num))       #100 to hex is 0x64

2.2 使用format字符串格式化

#1. 位置参数
print("{0} is {1} years old".format("tom", 28))            #tom is 28 years old
print("{} is {} years old".format("tom", 28))             #tom is 28 years old
print("Hi, {0}! {0} is {1} years old".format("tom", 28))      #Hi, tom! tom is 28 years old

#2. 关键字参数
print("{name} is {age} years old".format(name = "tom", age = 28))    #tom is 28 years old

#3. 下标参数
li = ["tom", 28]
print("{0[0]} is {0[1]} years old".format(li))          #tom is 28 years old
原文地址:https://www.cnblogs.com/xiaoxiamiaichiyu/p/14583933.html