python编码基础--字符串与它的相关操作

简介: python编码基础--字符串与它的相关操作

1、字符串单个元素取值

st='abc'
print(st[0]) #结果为a
for i  in st:
    print(i)#结果为a、b、c、

       可以使用for循环进行遍历取值

       可以使用下标进行取值

2、字符串切片

字符串变量名[m:n:k]

st='abcdefg'
print(st[0:6:1])#运行结果为abcdef

m索引起始位置,n索引结束位置+1,k步长(默认为1)

3、字符串调用内置函数

字符串变量名.upper()

.lower()

.title()

st='AbC'
print(st.upper())#结果为ABC
print(st.lower())#结果为abc
print(st.title())#结果为Abc

4、查找字符串

字符串变量名.find(字符串)

print(st.find('g'))#结果为6

5、字符串的替换:

字符串变量名.replace(替换目标,替换的值,替换次数)

如果没有替换次数,默认全部替换

st='abcdefgaba'
print(st.replace('a','A'))#结果为AbcdefgAbA,a全部替换成A
print(st.replace('a','A',2))#结果为AbcdefgAba,a两次替换成A

6、字符串的拼接

1、“+”加号拼接

2、格式化输出:

print("未来的大佬是就是%s"%,name)

%s,%d(digital数字),%f(默认精确到后6位), %.2f(保留2位有效小数)

3、{}.format (...)

# 大括号里的索引可以相同,但是不能为空

c_1="{1} love {1}".format("I","you","very","much")

print(c_1)

# 大括号里的索引可以乱序,但是不能超出索引范围

c_2="{3} love {2}{3}{0}".format("I","you","very","much","好的")

# 当大括号里为空时,默认按照顺序赋值,且有几个{}就附几个值,如果值少了就会报错

4、join()函数

语法:  'sep'.join(seq)

参数说明

sep:分隔符。可以为空

seq:要连接的元素序列、字符串、元组、字典

上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串

返回值:返回一个以分隔符sep连接各个元素后生成的字符串

#对序列进行操作(分别使用' '与':'作为分隔符)

>>> seq1 = ['hello','good','boy','doiido']

>>> print ' '.join(seq1)

hello good boy doiido

>>> print ':'.join(seq1)

hello:good:boy:doiido

#对字符串进行操作

>>> seq2 = "hello good boy doiido"

>>> print ':'.join(seq2)

h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o

#对元组进行操作

>>> seq3 = ('hello','good','boy','doiido')

>>> print ':'.join(seq3)

hello:good:boy:doiido

#对字典进行操作

>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}

>>> print ':'.join(seq4)

boy:good:doiido:hello

7、字符串分割:

.split(字符)

st='abcdefgaba'
print(st.split())#结果:['abcdefgaba']
print(st.split('c')) #结果:['ab', 'defgaba']


相关文章
|
5月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
391 100
|
5月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
545 99
|
5月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
5月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
5月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
5月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
6月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
407 0
|
6月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。
|
6月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
372 92

推荐镜像

更多