002---Python基本數據類型--字符串

字符串javascript

 

 

 

字符串的定義與建立

 

定義:字符串是一個有序的字符集合,用來存儲和表示文本信息。用雙引和單引表示。是一種不可變類型。

 

建立:

In [9]:
s = 'Hello Python'
print(s)
 
Hello Python
 

經常使用操做:

In [1]:
# 索引和切片
s = 'Python'
print(s[1])   # y
print(s[-1])  # n
print(s[1:4]) # yth  顧頭不顧尾
 
y
n
yth
In [2]:
# capitalize()  首字母大寫  
s = 'hello python'
print(s.capitalize())  # Hello python
 
Hello python
In [3]:
# upper()  lower()  全大寫和全小寫
s1 = 'hello python'
s2 = 'HELLO PYTHON'
print(s1.upper())  # Hello python
print(s2.lower())  # hello python
 
HELLO PYTHON
hello python
In [4]:
# title()  每一個隔開(特殊字符和數字)的單詞的首字母大寫
s = 'life is short you need python'
print(s.title())    # Life Is Short You Need Python
 
Life Is Short You Need Python
In [11]:
# center()  兩邊按指定字符填充  居中
s = 'python'
print(s.center(20,'-'))  # -------python-------
 
-------python-------
In [10]:
#  len()  長度  字符數
s = 'i love you jiang zi ya'
print(len(s))  # 22
s1 = '我喜歡你'
print(len(s1)) # 4
 
22
4
In [16]:
# startswith()  判斷是否以什麼什麼開頭  支持指定起始和終止
s = 'jiang ziya'
print(s.startswith('jiang'))     # True
print(s.startswith('ziya'))      # False
print(s.startswith('jiang',0,5)) # True
print(s.startswith('jiang',0,4)) # False
 
True
False
True
False
In [19]:
# find()  查找每一個字符的索引  沒找到返回-1  支持指定起始和終止
s = 'jiang zi ya'
print(s.find('z'))  
print(s.find('zi'))
print(s.find('Jiang'))
 
6
6
-1
In [20]:
# index()  查找每一個字符的索引  沒找到報錯
print(s.index('z'))  
print(s.index('zi'))
# print(s.index('Jiang'))
 
6
6
 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-20-ff6187789150> in <module>
      2 print(s.index('z'))
      3 print(s.index('zi'))
----> 4print(s.index('Jiang'))

ValueError: substring not found
In [36]:
# strip()  去除兩邊的指定字符串  默認刪空格  rstrip() 左邊  lstrip()  右邊
s = '    python   '
print(s.strip())
print(s.strip(''))
print(s.strip(' '))
print(''.center(20,'-'))
s1 = '*%jiang*%wei*%%%%'
print(s1.strip('*%'))
 
python
    python   
python
--------------------
jiang*%wei
In [46]:
# count() 計算某個字符的個數 支持指定起始和終止位置
s = 'Python python'
print(s.count('t'))
print(s.count('jiang'))
 
2
0
In [58]:
# split()  按照指定字符切割  默認按照空格切割  返回列表
s = ' i love you '
print(s.split())
print(s.split(' '))

s1 = '--he--he--he--'
print(s1.split('--'))
 
['i', 'love', 'you']
['', 'i', 'love', 'you', '']
[' i love you ']
['', 'he', 'he', 'he', '']
In [61]:
# replace() 替換 能夠指定替換數
s = 'who are you who are you who are you'
print(s.replace('you','she'))
print(s.replace('you','she',2))
 
who are she who are she who are she
who are she who are she who are you
In [69]:
# is系列
name = 'jiangziya1'
print(name.isalpha())  # 判斷字符串是否由字母組成
print(name.isalnum())  # 判斷字符串是否由數字和字母組成
print(name.isdigit())  # 判斷字符串是否右數字組成
 
False
True
False
相關文章
相關標籤/搜索