python----基础知识

1、拼接

基本语法如下:
result_string = source_string1 + source_string2
注释
source_string1:待合并的第一个字符串;
source_string2:待合并的第二个字符串;
result_string:合并后的字符串。
例1

first_name = 'Zhang'
last_name = 'san'
full_name = first_name + " " + last_name
print(full_name)在这里插入代码片

2、字符长度

基本语法:
length = len(target_string)
注释
target_string: 目标字符串变量;
length: 保存字符串长度的变量;
len: 获取字符串长度的语法关键词。
例2

 #coding=utf-8
# 创建一个字符串变量,获取其长度并打印出来
color = 'It is red'
length = len(color)
print (length)
# 直接在len函数中引入字符串内容获得其长度,然后打印出来
print(len('This is a circle!'))

3、大小写转换

基本语法:
将源字符串转换为大写并存入upper_string变量
upper_string = source_string.upper()
将源字符串转换为小写并存入lower_string变量
lower_string = source_string.lower()
将源字符串每个词首字母转换为大写并存入title_string变量 title_string = source_string.title()
例3

# coding=utf-8
# 创建一个字符串say_hello
say_hello = 'Dear my Daughter'
# 使用upper()方法对say_hello字符串进行处理
upper_say_hello = say_hello.upper()
print (say_hello+"\n")
输出为
Dear my Daughter

4、去除首尾空格及特殊字符

基本语法:
strip_string1 = source_string.strip()
string_strip2 = source_string.strip(target_char)
注释
source_string:待处理的源字符串;
strip_string1和strip_string2:处理后的字符串;
target_char:需要从源字符串首尾去除的特定字符。
例4

# coding = utf-8
# 创建一个字符串hello_world
hello_world = '  **The world ** is big!*    '
# 利用strip()方法处理hello_world字符串
blank_hello_world = hello_world.strip()
char_hello_world = hello_world.strip('TH *')
# 打印输出转换后的字符串
print(blank_hello_world)
print(char_hello_world)
输出为
**The world ** is big!*
he world ** is big!

5、字符串查找

基本语法:source_string.find(sub_string)
注释
source_string:源字符串;
sub_string:待查的目标子字符串;
find:字符串查找方法的语法关键字。
例5

# coding=utf-8
# 创建一个字符串
source_string = 'The past is gone and static'
# 查看"past"在source_string字符串中的位置
print(source_string.find('past'))
# 查看"love"在source_string字符串中的位置
print(source_string.find('love'))
输出结果:
4
-1

可以看出若未找到寻找字符即返回-1

6、字符串替换

基本语法:source_string.replace(old_string, new_string)
注释
source_string:待处理的源字符串;
old_string:被替换的旧字符串;
new_string:替换的新字符串;
replace:字符串替换方法的语法关键词。
例6

# coding = utf-8
# 创建一个字符串circle
source_string = 'The world is big'
# 利用replace()方法用子串"small"代替子串"big"
print(source_string.replace('big','small'))
输出结果:

The world is small

7、字符串分割

基本语法:source_string.split(separator)
注释
source_string:待处理的源字符串;
separator:分隔符;【如果不提供分隔符,则程序会默认把空格(制表、换行等)作为分隔符。】
split:字符串分割方法的关键词。
例7

# coding = utf-8
# 待处理字符串source_string
source_string = '1+2+3+4+5'
# 利用split()方法,按照`+`和`/`对source_string字符串进行分割
print(source_string.split('+'))
print(source_string.split('/'))
输出结果:
['1', '2', '3', '4', '5']
['1+2+3+4+5']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值