python基础--字符串

参考:https://www.runoob.com/python/python-strings.htmlhtml

Python有五个标准的数据类型:
    Numbers(数字)
    String(字符串)
    List(列表)
    Tuple(元组)
    Dictionary(字典)

  不可改变的数据类型:数字,字符串,元组python

  可变的数据类型:列表,字典git

 

一、python3.x的input():python3.x

  将键盘输入的内容(字符串)赋给变量aapi

a = input("输入一个数字:")
print(a)
print(type(a)) # 打印变量a的类型
b = 2

if int(a) > 1:
    #print("a的值为%s"%a)
    print("a的值为%s,b的值为%s"%(a, b))

 

二、字符串与数值类型的转换post

a = input("输入一个字符串:")
print("变量a的值为:%s"%a)
print(type(a)) # 打印变量a的类型
a = int(a) # 字符串 => int
print(type(a))
a = str(a) # int => 字符串
print(type(a))

 

三、len(字符串变量): 字符串长度spa

a = input("输入一个数字:")
print("变量a的值为:%s"%a)
print("变量a的长度为:%s"%len(a))

 

四、字符串的用法code

a = "hello"
b = ' world'
print(a + b) # 字符串拼接

print("a" * 10) # 打印10个a

c = "a+b=%s"%(a+b)
print(c)

 

  字符串下标:从0开始htm

a = "hello"

for s in a:
    print(s)
    
print("=" * 50)
i = 0
while i < len(a):
    print("字符串a的第%d个字符为:%s"%(i, a[i]))
    i += 1

  字符串切片blog

a = "hello"
print(a[0:3]) # 结果:hel.包左不包右,索引范围[0,2]
print(a[0:-2]) # 结果:hel.包左不包右, 从下标0开始,直到倒数第2个(不包含)
print(a[0:len(a)]) # 相对于print(a[0:])
print(a[0:-1:2]) # 起始位置:终止位置:步长

  字符串倒序

a = "hello"
# 字符串倒序
print(a[len(a)::-1])
print(a[-1::-1])
print(a[::-1])

 

五、字符串常见操做

  字符串方法

 

a = "helloworldhello"
# find
print(a.find("world")) # 第一次找到"world"的索引
print(a.rfind("hello")) # 从右边开始搜索,第一次找到"hello"的索引
print(a.find("haha")) # 找不到,结果:-1

# index
print(a.index("hello"))
print(a.rindex("hello"))
#print(a.index("haha")) # index与find的区别:find找不到结果为-1,index找不到抛异常
#print(a.rindex("haha"))

# count(str, start=0, end = len(mystr)):返回str在start和end之间mystr里面出现的次数
print(a.count("hello"))

# replace:把mystr中的str1替换成str,指定了count,则替换不超过count次
# mystr.replace(str1, str2, mystr.count(str)), 原来的字符串不变
b = a.replace("hello", "HELLO", 2)
print("a的值为%s, b的值为%s"%(a,b)) # a的值为helloworldhello, b的值为HELLOworldHELLO

# split
mystr = "hello world hello python"
array = mystr.split(" ")
print("mystr的值%s"%mystr) # 原来的字符串不变
for str in array:
    print(str)
    
# capitalize:把字符串的第一个字符大写
# title:把字符串的每一个单词首字母大写
print(a.title()) #Helloworldhello
print(mystr.title()) #Hello World Hello Python

# startswith/endswith
print(a.startswith("hello")) # True
print(a.startswith("world")) # False

# lower/upper:原来的字符串不变
print(a.upper()) # HELLOWORLDHELLO
mystr = "  hello python  "
#print(mystr.center(20))
print(mystr.strip()) # 去除先后空格

# string.isalnum():若是 string 至少有一个字符而且全部字符都是字母或数字则返回 True,不然返回 False
# string.isalpha():若是 string 至少有一个字符而且全部字符都是字母则返回 True,不然返回 False
# string.isdigit():若是 string 只包含数字则返回 True 不然返回 False.

# join
strArray = ["aaa", "bbb", "ccc"]
regex = ", "
str = regex.join(strArray)
print(str)
相关文章
相关标签/搜索