python学习笔记:string的打印

(一)换行打印:

print("""abc
def""")

#等价于:
print("abc")
print("def")

#输出: 
#abc
#def

(二)索引特定位置字符:

           即引用字符串s中特定位置字符。从0开始,如果为负数X等价于len(s)-X

s="abcdefg"
print(s[0])           #a
print(s[1])           #b
print(s[2])           #c
print("------")       
print(s[len(s)-1])    #g
print(s[len(s)])      #error
print(s[-1])          #==s[len(s)-1]    g

(三)截取一段字符串:

          使用s[ : ]:截取字符串中一段字符,遵循左闭右开原则,从0开始,到X-1结束。

s = "abcdefgh"
print(s)
#a range of characters   取一段字符
print(s[0:3])               #abc
print(s[1:3])               #bc
print("-----------")
print(s[2:3])               #c
print(s[3:3])               #None

#with default parameters 缺省参数
print(s[3:])                #defgh
print(s[:3])                #abc
print(s[:])                 #abcdefgh
print("-----------")        

#with a step parameter   步长  
print("This is not as common, but perfectly ok.")
print(s[1:7:2])             #bdf    2是步长,即输出1、1+2、1+2+2 (1+2+2+2=7超出范围)
print(s[1:7:3])             #be     3是步长,即输出1、1+3  (1+3+3=7超出范围)

(三)翻转字符串:

           reversing:s[ : : -1],最好的方式写自定义函数,清楚明了

s = "abcdefgh"

print("This works, but is confusing:")
print(s[::-1])

print("This also works, but is still confusing:")
print("".join(reversed(s)))

print("Best way: write your own reverseString() function:")

def reverseString(s):
    return s[::-1]

print(reverseString(s)) # crystal clear!

(四)引用常量:

import string
print(string.ascii_letters)   # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz
print("-----------")
print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits)          # 0123456789
print("-----------")
print(string.punctuation)     # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
print(string.printable)       # digits + letters + punctuation + whitespace
print("-----------")
print(string.whitespace)      # space + tab + linefeed + return + ...

☆☆关于string模块(形式:string.)VS. python内置函数(形式:S.method(XX))

早期,使用import string 可引用专门的string模块,但后来由于众多的python使用者的建议,从python2.0开始,string方法改为用S.method()的形式调用,只要S是一个字符串对象就可以这样使用,而不用import。

为了保持向后兼容,现在的python中仍然保留了一个string的module,其中定义的方法与S.method()是相同的,这些方法都最后都指向了用S.method()调用的函数。

要注意,S.method()能调用的方法比string的module中的多,比如isdigit()、istitle()等就只能用S.method()的方式调用。

(五)字符串连接的“+”和“*”:

print("abc"+"def")      #abcdef
print("abc"*3)          #abcabcabc

(六)判断:

1、字符串中是否存在某个字符串 “in”:

print("ring" in "strings")     #True
print("wow" in "amazing!")     #False
print("Yes" in "yes!")         #False
print("" in "No way!")         #True

2、S.isalnum()或者str.isalnum(S):判断字符串s是否全部由字母和数字组成,返回True/False  

3、S.isalpha()或者str.isalpha(S):判断字符串s是否只由字母组成,返回True/False

4、S.isdigit()或者isdigit(S):判断字符串s是否只由数字组成,返回True/False

5、S.isupper()或者str.isupper(S):判断字符串s是否全部为大写字母,返回True/False

6、S.islower()或者str.islower(S):判断字符串s是否全部为小写字母,返回True/False

7、S.isspace()或者str.isspace(S):判断字符串s是否只由空格组成,返回True/False

# Run this code to see a table of isX() behaviors
def p(test):
    print("True     " if test else "False    ", end="")
def printRow(s):
    print(" " + s + "  ", end="")
    p(s.isalnum())
    p(s.isalpha())
    p(s.isdigit())
    p(s.islower())
    p(s.isspace())
    p(s.isupper())
    print()
def printTable():
    print("  s   isalnum  isalpha  isdigit  islower  isspace  isupper")
    for s in "ABCD,ABcd,abcd,ab12,1234,    ,AB?!".split(","):
        printRow(s)
printTable()
上述代码输出: 
 s   isalnum  isalpha  isdigit  islower  isspace  isupper
 ABCD  True     True     False    False    False    True     
 ABcd  True     True     False    False    False    False    
 abcd  True     True     False    True     False    False    
 ab12  True     False    False    True     False    False    
 1234  True     False    True     False    False    False    
       False    False    False    False    True     False    
 AB?!  False    False    False    False    False    True

(七)编辑字符串:

1、s.lower():将字符串s中的大写字母转换为小写字母,数字不变

2、s.upper():将字符串s中的小写字母转换为大写字母,数字不变

3、s.replace(A,B,N):将字符串s中第N个A替换为B,并返回新的字符串,如N=0,则全部替换

4、s.strip(XX):将字符串s头尾XX部分移除,并返回新的字符串(不是s的任意部分)

print("This is nice. Yes!".lower())
print("So is this? Sure!!".upper())
print("   Strip removes leading and trailing whitespace only    ".strip())
print("This is nice.  Really nice.".replace("nice", "sweet"))
print("This is nice.  Really nice.".replace("nice", "sweet", 1)) # count = 1

print("----------------")
s = "This is so so fun!"
t = s.replace("so ", "")
print(t)
print(s) # note that s is unmodified (strings are immutable!)

(八)子字符串

1、s.count(sub, start=num1,end=num2):统计字符串中子字符串sub出现的次数,start(起始位置)、end(结束位置)可缺                                                                        省

2、s.startswith(sub,start=num1,end=num2):检查字符串[start,end]是否是以指定子字符串sub开头

3、s.endswith(suffix,start=num1,end=num2):检查字符串[start,end]是否是以指定子字符串suffix结尾

4、s.find(sub):检查字符串str是否有子字符串sub,返回子字符串sub的起始位置

5、s.index(sub):返回字符串str中子字符串sub的起始位置

print("This is a history test".count("is")) # 3
print("This IS a history test".count("is")) # 2
print("-------")
print("Dogs and cats!".startswith("Do"))    # True
print("Dogs and cats!".startswith("Don't")) # False
print("-------")
print("Dogs and cats!".endswith("!"))       # True
print("Dogs and cats!".endswith("rats!"))   # False
print("-------")
print("Dogs and cats!".find("and"))         # 5
print("Dogs and cats!".find("or"))          # -1
print("-------")
print("Dogs and cats!".index("and"))        # 5
print("Dogs and cats!".index("or"))         # crash!

猜你喜欢

转载自blog.csdn.net/xiaozhimonica/article/details/84566487