1.字符串的拼接
first_name = input()
last_name = input()
full_name = first_name + " " + last_name
print(full_name)
Python使用+来合并两个字符串,这种合并字符串的方法叫做拼接。其基本语法如下:
result_string = source_string1 + source_string2
2.字符串长度获取
Python提供了len()函数来计算并返回字符串的长度,即字符串中单个元素的个数。其基本语法如下:
length = len(target_string)
3.大小写转换
Python提供了upper()和lower()方法来对字符串进行大小写转换。其中,upper()会将字符串中的所有字符都转换为大写,lower()则将所有字符转换为小写。
除此之外,Python还贴心的提供了title()方法将字符串所有单词的首字母变成大写,而其他字母依然小写。各个方法的具体语法如下:
upper_string = source_string.upper()
lower_string = source_string.lower()
title_string = source_string.title()
4.去除字符首尾串空格
Python提供了strip()方法,可以去除字符串两侧(不包含内部)全部的空格;使用该方法,也可以通过指定参数,去除两侧指定的特定字符
注意:在指定参数时,如果参数是多个字符,则该方法会将多个字符逐个去比对进行删除(区分大小写),直到首尾两侧没有匹配的字符为止。但是,该方法对字符串中间的字符没有影响。
其基本语法如下:
strip_string1 = source_string.strip()
string_strip2 = source_string.strip(target_char)
# 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.字符串查找
Python提供了内置的字符串查找方法find(),利用该方法可以在一个较长的字符串中查找子字符串。如果该字符串中有一个或者多个子字符串,则该方法返回第一个子串所在位置的最左端索引;若没有找到符合条件的子串,则返回-1。
find()方法的基本使用语法如下:
source_string.find(sub_string)
# 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'))
6.字符串替换
Python提供了replace()方法,用以替换给定字符串中的子串,其基本使用语法如下:
source_string.replace(old_string, new_string)
# coding = utf-8
# 创建一个字符串circle
source_string = 'The world is big'
# 利用replace()方法用子串"small"代替子串"big"
print(source_string.replace('big','small'))
7.字符串的分割
Python提供了split()方法实现字符串分割。该方法根据提供的分隔符将一个字符串分割为字符列表,如果不提供分隔符则程序会默认把空格(制表、换行等)作为分隔符。其基本使用语法如下:
source_string.split(separator)
# 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’]