python入門到放棄(四)-基本數據類型之str字符串

1.概念

python中用',",''',"""引起來的內容稱爲字符串,可以保存少量數據並進行相應的操作

 

#先來看看str的源碼寫了什麼,方法:按ctrl+鼠標左鍵點str

class int(object):
    """
    int(x=0) -> int or long
    int(x, base=10) -> int or long
    
    Convert a number or string to an integer, or return 0 if no arguments
    are given.  If x is floating point, the conversion truncates towards zero.
    If x is outside the integer range, the function returns a long instead.
    
    If x is not a number or if base is given, then x must be a string or
    Unicode object representing an integer literal in the given base.  The
    literal can be preceded by '+' or '-' and be surrounded by whitespace.
    The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
    interpret the base from the string as an integer literal.
    >>> int('0b100', base=0)
    """
    def bit_length(self): 
        """ 返回表示該數字的時佔用的最少位數 """
        """
        int.bit_length() -> int
        
        Number of bits necessary to represent self in binary.
        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        """
        return 0

    def conjugate(self, *args, **kwargs): # real signature unknown
        """ 返回該複數的共軛複數 """
        """ Returns self, the complex conjugate of any int. """
        pass

    def __abs__(self):
        """ 返回絕對值 """
        """ x.__abs__() <==> abs(x) """
        pass

    def __add__(self, y):
        """ x.__add__(y) <==> x+y """
        pass

    def __and__(self, y):
        """ x.__and__(y) <==> x&y """
        pass

    def __cmp__(self, y): 
        """ 比較兩個數大小 """
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __coerce__(self, y):
        """ 強制生成一個元組 """ 
        """ x.__coerce__(y) <==> coerce(x, y) """
        pass

    def __divmod__(self, y): 
        """ 相除,得到商和餘數組成的元組 """ 
        """ x.__divmod__(y) <==> divmod(x, y) """
        pass

    def __div__(self, y): 
        """ x.__div__(y) <==> x/y """
        pass

    def __float__(self): 
        """ 轉換爲浮點類型 """ 
        """ x.__float__() <==> float(x) """
        pass

    def __floordiv__(self, y): 
        """ x.__floordiv__(y) <==> x//y """
        pass

    def __format__(self, *args, **kwargs): # real signature unknown
        pass

    def __getattribute__(self, name): 
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        """ 內部調用 __new__方法或創建對象時傳入參數使用 """ 
        pass

    def __hash__(self): 
        """如果對象object爲哈希表類型,返回對象object的哈希值。哈希值爲整數。在字典查找中,哈希值用於快速比較字典的鍵。兩個數值如果相等,則哈希值也相等。"""
        """ x.__hash__() <==> hash(x) """
        pass

    def __hex__(self): 
        """ 返回當前數的 十六進制 表示 """ 
        """ x.__hex__() <==> hex(x) """
        pass

    def __index__(self): 
        """ 用於切片,數字無意義 """
        """ x[y:z] <==> x[y.__index__():z.__index__()] """
        pass

    def __init__(self, x, base=10): # known special case of int.__init__
        """ 構造方法,執行 x = 123 或 x = int(10) 時,自動調用,暫時忽略 """ 
        """
        int(x=0) -> int or long
        int(x, base=10) -> int or long
        
        Convert a number or string to an integer, or return 0 if no arguments
        are given.  If x is floating point, the conversion truncates towards zero.
        If x is outside the integer range, the function returns a long instead.
        
        If x is not a number or if base is given, then x must be a string or
        Unicode object representing an integer literal in the given base.  The
        literal can be preceded by '+' or '-' and be surrounded by whitespace.
        The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
        interpret the base from the string as an integer literal.
        >>> int('0b100', base=0)
        # (copied from class doc)
        """
        pass

    def __int__(self): 
        """ 轉換爲整數 """ 
        """ x.__int__() <==> int(x) """
        pass

    def __invert__(self): 
        """ x.__invert__() <==> ~x """
        pass

    def __long__(self): 
        """ 轉換爲長整數 """ 
        """ x.__long__() <==> long(x) """
        pass

    def __lshift__(self, y): 
        """ x.__lshift__(y) <==> x<<y """
        pass

    def __mod__(self, y): 
        """ x.__mod__(y) <==> x%y """
        pass

    def __mul__(self, y): 
        """ x.__mul__(y) <==> x*y """
        pass

    def __neg__(self): 
        """ x.__neg__() <==> -x """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): 
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __nonzero__(self): 
        """ x.__nonzero__() <==> x != 0 """
        pass

    def __oct__(self): 
        """ 返回改值的 八進制 表示 """ 
        """ x.__oct__() <==> oct(x) """
        pass

    def __or__(self, y): 
        """ x.__or__(y) <==> x|y """
        pass

    def __pos__(self): 
        """ x.__pos__() <==> +x """
        pass

    def __pow__(self, y, z=None): 
        """ 冪,次方 """ 
        """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
        pass

    def __radd__(self, y): 
        """ x.__radd__(y) <==> y+x """
        pass

    def __rand__(self, y): 
        """ x.__rand__(y) <==> y&x """
        pass

    def __rdivmod__(self, y): 
        """ x.__rdivmod__(y) <==> divmod(y, x) """
        pass

    def __rdiv__(self, y): 
        """ x.__rdiv__(y) <==> y/x """
        pass

    def __repr__(self): 
        """轉化爲解釋器可讀取的形式 """
        """ x.__repr__() <==> repr(x) """
        pass

    def __str__(self): 
        """轉換爲人閱讀的形式,如果沒有適於人閱讀的解釋形式的話,則返回解釋器課閱讀的形式"""
        """ x.__str__() <==> str(x) """
        pass

    def __rfloordiv__(self, y): 
        """ x.__rfloordiv__(y) <==> y//x """
        pass

    def __rlshift__(self, y): 
        """ x.__rlshift__(y) <==> y<<x """
        pass

    def __rmod__(self, y): 
        """ x.__rmod__(y) <==> y%x """
        pass

    def __rmul__(self, y): 
        """ x.__rmul__(y) <==> y*x """
        pass

    def __ror__(self, y): 
        """ x.__ror__(y) <==> y|x """
        pass

    def __rpow__(self, x, z=None): 
        """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
        pass

    def __rrshift__(self, y): 
        """ x.__rrshift__(y) <==> y>>x """
        pass

    def __rshift__(self, y): 
        """ x.__rshift__(y) <==> x>>y """
        pass

    def __rsub__(self, y): 
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rtruediv__(self, y): 
        """ x.__rtruediv__(y) <==> y/x """
        pass

    def __rxor__(self, y): 
        """ x.__rxor__(y) <==> y^x """
        pass

    def __sub__(self, y): 
        """ x.__sub__(y) <==> x-y """
        pass

    def __truediv__(self, y): 
        """ x.__truediv__(y) <==> x/y """
        pass

    def __trunc__(self, *args, **kwargs): 
        """ 返回數值被截取爲整形的值,在整形中無意義 """
        pass

    def __xor__(self, y): 
        """ x.__xor__(y) <==> x^y """
        pass

    denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分母 = 1 """
    """the denominator of a rational number in lowest terms"""

    imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 虛數,無意義 """
    """the imaginary part of a complex number"""

    numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 分子 = 數字大小 """
    """the numerator of a rational number in lowest terms"""

    real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """ 實屬,無意義 """
    """the real part of a complex number"""

int
int

 

2.字符串的索引和切片

#索引

#索引就是下標,切記,下標從0開始
s = "大河向東流去"
print(s[0])  #大  #從0開始取
print(s[1])  #
print(s[2])  #
print(s[3])  #
print(s[4])  #
print(s[5])  #
print(s[6])  #索引不能超過邊界,要不然會報錯

print(s[-1])  #-1就是倒着從後面取
print(s[-2])
print(s[-3])
print(s[-4])
print(s[-5])
print(s[-6])

#切片

#切片[起始位置:結束位置]
#特點:1、顧頭不顧尾
      2、只能從左往右切

#例子:
s = "改革春風吹滿面"
print(s[1:3]) #從1切到3,但是取不到3
#革春 #因爲是下標從0開始,所以1就是革
print(s[1:]) #從1開始切,切到結尾 #革春風吹滿面

print(s[:2]) #從頭開始切到2
#改革

print(s[:]) #從頭到尾
#改革春風吹滿面
print(s[-1:-3]) #這樣從右往左切會是空值 print(s[-3:-1]) #只能從左往右切
#吹滿

#跳着取值,步長

#步長:如果是整數,就從左往右取,如果是負數就從右往左取
print(s[-1:-3:-1]) # - 表示反方向,從右往左
print(s[3:9:2])    #表示3到9中間每隔2位取一個
print(s[4:10:3])   #表示4到10中間每隔3取一位
print(s[-3:-9:-2]) #從右往左每個2位取一個

 

3.字符串相關操作

#注意點:

#注意:字符串是不可變的對象,所有任何操作對源字符串是不會有任何影響的
#例如
s = "I am a teacher"
s.capitalize()
print(s) #I am a teacher

 

#1.大小寫的相互轉換

#關鍵字
# capitalize():將首字母變成大寫
# lower():全部替換成小寫
# upper():全部替換成大寫
# swapcase():大小寫互換
# casefold():轉換成小寫
# titile():每個被特殊字符隔開的首字母大寫

#例子:

s = "This is teacher and Student"


s1 = s.capitalize()  #將首字母變成大寫
print(s1) #This is teacher and student

s2 = s.lower()   #全部轉換成小寫
print(s2) #this is teacher and student

s3 = s.upper()  #全部轉換成大寫
print(s3) #THIS IS TEACHER AND STUDENT

s4 = s.swapcase() #大小寫互相轉換
print(s4) #tHIS IS TEACHER AND sTUDENT

s5 = s.casefold()  #轉換成小寫,這個能識別出所有字母,但lower有些不支持
print(s5) #this is teacher and student
View Code

 

#2.切來切去

#關鍵字
# center():內容居中
# strip():去掉左右兩端的空格
# lstrip():去掉左邊的空格
# rstrip():去掉右邊的空格
# replace(old,new):字符替換
# split():切割

#例子:

#1.拉長的長度:center()
s = "nb"
s1 = s.center(10,"#") #強行使用#號在原字符串左右兩端進行拼接,拼接成10個單位
print(s1)

# 更改tab的長度
s6 = "alex wusir\teggon"
print(s6)
print(s6.expandtabs())    # 可以改變\t的⻓長度, 默認⻓長度更更改爲8

#2.去空格
s = "  guoke  boy  is  "
s1 = s.strip()  #默認去掉兩邊的空格
print(s1)  #打印出來的時候就會發現兩邊沒有空格

s2 = s.lstrip()  #去掉左邊的空格
print(s2)

s3 = s.rstrip()  #去掉右邊的空格
print(s3)

#strip()應用
# 設置用戶交互式登陸的時候,如果不加strip(),當用戶如輸入用戶名後面加了空格,那麼就會報錯
# 如果加了strip(),就可以去掉兩邊的空格
username = input("請輸入用戶名:").strip()
password = input("請輸入密碼:").strip()
if username == 'cw' and password == '123':
    print("登陸成功")
else:
    print("登陸失敗")

#指定去掉的元素
s = "nb boy guoke nb nb tiantian sb"
print(s.strip("nb"))

#3.字符串替換:replace()
s = "student,戰狼,teacher,小豬佩奇_eat,少年的你"
s1 = s.replace("少年的你","中國機長")  #將少年的你替換成中國機長
s2 = s.replace("小豬","貓貓")  #將小豬替換成貓貓
print(s1,s2)

s3 = s.replace('e','nb',2)  #將e替換成nb,替換前兩個
print(s3)

#4.字符串切割:split()
s4 = "fd,fwe,tet,rer,aggo"
lst = s4.split(",")  #字符串切割,根據,進行切割
print(lst)
 
s5 = s4.split("e")  #使用什麼進行切割就會損失掉什麼
print(s5)


#坑點
# s7 = "湖邊哈哈美麗美麗湖人湖邊"
# lst = s7.split("湖邊") #如果切割符在左右兩端,那麼一定會出現空字符串
# print(lst)
# print(bool(lst)) #可以看到返回是True,因爲是空字符串
View Code

 

#3.查找相關

#關鍵字:
# startswith():判斷是否以xxx開頭
# endswith():判斷是否以xxx結尾
# count():查看那個字符出現的次數
# find():查看關鍵字在什麼位置,沒有找到的話就返回-1
# index():求索引的位置:如果沒找到字符串就會報錯

#例子:

s = "我是一個boy,我喜歡python,java等編程語言"

s1 = s.startswith("我是一個")  #判斷是否以我開頭,如果是就會返回True,否則返回False
print(s1) #True

s2 = s.startswith("boy")  #可以看出返回的結果是False
print(s2) #False

s3 = s.endswith("語言")  #判斷是否以"語言"位結尾,是就會返回True,否則返回False
print(s3) #True

s4 = s.endswith("我們")  #可以看出不是以我們結尾就返回False
print(s4) #False

s5 = s.count("a")  #統計"a"出現的次數
print(s5) #2

s6 = s.find("java")  #查看Java出現的位置,只找第一次出現的位置,沒有就返回-1
print(s6) #18

s7 = s.find("a",20,29)  #切片找,指定位置找a,從20-29中間找有沒有a
print(s7) #21

s8 = s.index("java")   #查找java的位置
print(s8) #18

# s9 = s.index("z")  #index如果沒有查找到的話就會報錯,寫程序的就不用使用index,否則整個程序都會崩掉了,使用find
# print(s9)
View Code

 

#4.條件判斷相關

#關鍵字
# isalnum():判斷是否由字母和數字組成
# isalpha():判斷是否由字母組成
# isdigit():判斷是否由數字組成
# isdecimal():判斷是否由數字組成
# isnumeric():判斷是否由數字組成 #中文也識別

#例子:

s1 = "12345"
s2 = "123abc"
s3 = "abcde"
s4 = "_abdf@"
s5 = "壹仟叄佰肆拾"
print(s1.isdigit())  #判斷是否由數字組成,如果是就返回True,否則Fase
#True
print(s2.isalnum())  #判斷是否由數字和字母組成
#True
print(s3.isalpha())  #判斷是否由字母組成
#True
print(s5.isnumeric()) #判斷是否由數字組成,可以是大寫的,如果是字符串就報錯
#True
print(s1.isdecimal()) #判斷是否由數字組成
#True

#練習,用算法判斷某一個字符串是否是小數
s17 = "-123.12"
s17 = s17.replace("-", "")  # 替換掉負號
if s17.isdigit():
    print("是整數")
else:
    if s17.count(".") == 1 and not s17.startswith(".") and not s17.endswith("."):
        print("是⼩小數")
    else:
        print("不不是⼩小數")
#過程理解:首先將符號替換成空字符串,然後進入判斷變量是否是數字組成
#很顯然是沒有由數字組成,所有就走else,又進入如果判斷,如果統計點符號等於1
#和不是以點開頭和不是以點結尾,滿足條件,所以打印是小小數
View Code

 

#5.計算字符串的長度

#關鍵字
#len():計算機字符串的長度

#例子:

s1 = "我是你的小呀小蘋果"
ret = len(s1)
print(ret) #9
#注意:len()是python的內置函數,所以訪問方式也不一樣,記住len()和print()方式一樣

 

#6.join

#join:將列表轉換成字符串
#注意:join(裏面放的是可迭代對象)

#例子

 lst = ["蔣小雨","張衝","魯炎"] s = "_".join(lst) print(s) #蔣小雨_張衝_魯炎

 s = "_".join("武黑臉") print(s) #武_黑_臉

#將字符串轉換成列表:split() s = "馬雲,移動,雷子" lst = s.split(",") print(lst) #['馬雲', '移動', '雷子']

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章