python中字符串详解

1、定义字符串

Python中定义字符串是用单引号或者双引号引起来

注意:如果字符串中的内容需要用到双引号,那么定义字符串时使用单引号,但是在平常的开发中最好还是用双引号定义字符串

str1 = "hello python"

str2 = '我的外号是"海绵宝宝"'

print(str1)
print(str2)

# 输出结果

hello python
我的外号是"海绵宝宝"

2、字符串取值  字符串[索引]

str2 = '我的外号是"海绵宝宝"'

print(str2[3])

# 返回结果

3、字符串遍历

str2 = '我的外号是"海绵宝宝"'

for temp in str2:

    print(temp)

# 返回结果

我
的
外
号
是
"
海
绵
宝
宝
"

4、字符串统计

4-1统计字符串的长度  len函数

hello_str = "hello hello"

print(len(hello_str))

# 返回结果

11

4-2统计大字符串中某一个子字符串出现的次数  str.count方法

hello_str = "hello hello"

# 统计大字符串中某一个小字符串出现的次数

print(hello_str.count("l"))
print(hello_str.count("ll"))
print(hello_str.count("abc"))
# 返回结果 
4
2
0

4-3获取字符串中第一次出现的某个子字符串的索引---str.index方法  注意:输入不存在的子字符串会报错

hello_str = "hello hello"

print(hello_str.index("l"))

# 返回结果

2

5.判断

#判断空白字符 也可以判断为空的转义字符
 
 	

spase_str = " "
spase_str1 = " 
	"

print(spase_str.isspace())
print(spase_str1.isspace())

# 返回结果:
True
True

# 判断字符中是否只包含数字

num_str = "1"
print(num_str)

print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())

# 返回结果
1
True
True
True

# 都不能判断小数 会返回flase
num_str1 = "1.1"
print(num_str1)

print(num_str1.isdecimal())
print(num_str1.isdigit())
print(num_str1.isnumeric())

# 返回结果
1.1
False
False
False

# Unicode字符串  ①   u00b2

num_str2 = ""
print(num_str2)

print(num_str2.isdecimal())
print(num_str2.isdigit())
print(num_str2.isnumeric())

# 返回结果
①
False
True
True

num_str3 = "u00b2"
print(num_str3)

print(num_str3.isdecimal())
print(num_str3.isdigit())
print(num_str3.isnumeric())

# 返回结果
²
False
True
True

# 中文数字
num_str4 = "一千零一"
print(num_str4)

print(num_str4.isdecimal())
print(num_str4.isdigit())
print(num_str4.isnumeric())

# 返回结果

一千零一
False
False
True

 6.对齐

# 让下列字符串的内容居中对齐/右对齐/左对齐

poem = ["登鹳雀楼",
        "王之涣",
        "白日依山尽",
        "黄河入海流",
        "欲穷千里目",
        "更上一层楼"]

for poem in poem:
    print("|%s|" % poem.center(10," "))

# 输出结果:
|   登鹳雀楼   |
|   王之涣    |
|  白日依山尽   |
|  黄河入海流   |
|  欲穷千里目   |
|  更上一层楼   |

for poem1 in poem:
    print("|%s|" % poem1.rjust(10," "))

# 输出结果
|      登鹳雀楼|
|       王之涣|
|     白日依山尽|
|     黄河入海流|
|     欲穷千里目|
|     更上一层楼|

for poem2 in poem:
    print("|%s|" % poem2.ljust(10," "))
# 输出结果
|登鹳雀楼      |
|王之涣       |
|白日依山尽     |
|黄河入海流     |
|欲穷千里目     |
|更上一层楼     |
原文地址:https://www.cnblogs.com/hm-baobao/p/10060395.html