Self-study Python in 20 days with no basic knowledge | Day8 String string

Hello everyone, my name is Ning Yi.

A string is any text enclosed in English quotes.

Regardless of whether they are single quotes or double quotes, as long as they appear in pairs.

For example: 'abc', "Ning Yi", "hello", '123'

1. Get the string

If we need to get a certain value in the string, we can get it through [ ]. Note that the index of the string starts from 0.

name = "maoning836"
# 获取字符串第1个值,注意是从0开始name[0]# 输出 'm'
# 获取字符串第2个值name[1]# 输出 'a'
# 获取”maoning”这个单词,不包括最后一个字符name[0:7]name[:7]   # 这样写也可以,将0省略
# 获取后面3个数字’836'name[7:10]name[-3:]  # 这样写也可以,用负数索引

2. Process strings

a = "maoning"

b = "836"

(1) Splicing +

name = a + b# 输出 'maoning836'

(2) Replacement()

​​​​​​​

a.replace("mao","miao")# 输出 'miaoning'

(3) Length len()

​​​​​​​

len(a)# 输出 7

(4) Convert case 

​​​​​​​

# 转换成大写a.upper()# 输出 'MAONING'
# 转换成小写a.lower()# 输出 'maoning'

(5) Find find()

The find() method is used to detect whether a string contains a certain value. If included, returns the starting index of the value in the string. If not included, returns -1.

​​​​​​​

a.find("ning")# 输出 3a.find("nihao")# 输出 -1

(6) Judgment in

in is used to determine whether a certain value exists in a string. It is similar to the usage of find() above, but it will not return the index, but True or False.

​​​​​​​

"f" in a# 输出 False"mao" in a# 输出 True

You can also use not in, and the output result is just the opposite of in.

​​​​​​​

"mao"  not in a# 输出 False

(7) Split()

Use split() to split a string into a list

​​​​​​​

a.split("n")# 输出 ['mao', 'i', 'g']

3. Format string

String formatting is actually adding a placeholder to the string and inserting the value into the corresponding placeholder position.

What is more complicated is that strings in different formats have different placeholders, such as %d for integers and %f for floating point numbers.

For specific placeholders, please refer to this table:

usage:

First use the placeholder %s to occupy the position, then write %, followed by the value a to be placed above the placeholder

​​​​​​​

"My name is %s" % a# 输出 'My name is maoning'

This method is actually not commonly used by us, because if we directly use + for string splicing, it will have the same effect.

"My name is " + a

The usage of format strings is often used to format floating point numbers.

​​​​​​​​​​​​​​

c = 1.23456# 保留两个小数点'%.2f' % c# 输出 '1.23'# 保留4个小数点,甚至还能帮咱们四舍五入,太赞了'%.4f' % c# 输出 '1.2346'

Click to follow and get started with Python without getting lost~

Guess you like

Origin blog.csdn.net/shine_a/article/details/126641828