字符串或串(String)是由数字、字母、下划线组成的一串字符。
在 Python 中,字符串用单引号或者双引号括起来。
第1关:字符串的拼接:名字的组成
Python 中使用+
来合并两个字符串,这种合并字符串的方法叫做拼接。其基本语法如下:
String = String_one + String_two
本关的编程任务是补全src/Step1/full_name.py
文件中 Begin-End 区间的代码,实现如下功能:
-
将存放姓氏的字符串变量和存放名字的字符串变量拼接起来,中间用一个空格隔开,并将结果存储在
full_name
变量中; -
打印输出
full_name
变量。# coding=utf-8 # 存放姓氏和名字的变量 first_name = input() last_name = input() # 请在下面添加字符串拼接的代码,完成相应功能 ########## Begin ########## print(first_name+" "+last_name) ########## End ##########
测试输入:
Hu
dong
预期输出:
Hu dong
第2关:字符转换
对给定的字符串进行处理,包括字符串长度计算、大小写转换以及去除字符串前后空格等。
字符串长度获取
Python 提供了len()
函数来计算,并返回字符串的长度,即字符串中单个元素的个数。其基本语法如下:
length = len(target_string)
大小写转换
Python 提供了upper()
和lower()
方法,来对字符串进行大小写转换。其中,upper()
会将字符串中的所有字符都转换为大写,lower()
则将所有字符转换为小写。另外title()
方法可以将字符串所有单词的首字母变成大写,而其他字母依然小写。各个方法的具体语法如下:
# 将源字符串转换为大写并存入upper_string变量
upper_string = source_string.upper()
# 将源字符串转换为小写并存入lower_string变量
lower_string = source_string.lower()
# 将源字符串每个词首字母转换为大写并存入title_string变量
title_string = source_string.title()
去除字符串首尾空格
Python 提供了strip()
方法,可以去除字符串两侧(不包含内部)全部的空格。使用该方法,也可以通过指定参数,去除两侧指定的特定字符。
strip_string1 = source_string.strip()
string_strip2 = source_string.strip(target_char)
本关的编程任务是,补全src/Step2/method1.py
文件中 Begin-End 区间的代码,实现给定字符串的转换功能,具体要求如下:
-
step1 :将输入的源字符串
source_string
首尾的空格删除; -
step2 :将 step1 处理后的字符串的所有单词的首字母变为大写,并打印输出;
-
step3 :将 step2 转换后的字符串的长度打印输出。
# coding=utf-8
# 获取待处理的源字符串
source_string = input()
# 请在下面添加字符串转换的代码
########## Begin ##########
string_step1 = source_string.strip()
string_step2 = string_step1.title()
print(string_step2)
int_step3 = len(string_step2)
print(int_step3)
########## End ##########
测试输入:
Where there is a will,there is a way
预期输出:
Where There Is A Will,There Is A Way
36
第3关:字符串查找与替换
给定一个字符串,要利用 Python 提供的字符串处理方法,从该字符串中,查找特定的词汇,并将其替换为另外一个更合适的词。
字符串查找
Python 提供了内置的字符串查找方法find()
,利用该方法可以在一个较长的字符串中查找子字符串。如果该字符串中,有一个或者多个子字符串,则该方法返回第一个子串所在位置的最左端索引,若没有找到符合条件的子串,则返回-1
。find()
方法的基本使用语法如下:
source_string.find(sub_string)
字符串替换
Python 提供了replace()
方法,用以替换给定字符串中的子串。其基本使用语法如下:
source_string.replace(old_string, new_string)
字符串分割
Python 提供了split()
方法实现字符串分割。该方法根据提供的分隔符,将一个字符串分割为字符列表,如果不提供分隔符,则程序会默认把空格(制表、换行等)作为分隔符。其基本使用语法如下:
source_string.split(separator)
- 用
+
、/
还有空格作为分隔符,分割字符串:
本关的编程任务是,补全src/Step3/method2.py
文件中 Begin-End 区间的代码,实现如下功能:
-
step1 :查找输入字符串
source_string
中,是否存在day
这个子字符串,并打印输出查找结果; -
step2 :对输入字符串
source_string
执行字符替换操作,将其中所有的day
替换为time
,并打印输出替换后的字符串; -
step3 :对 step2 进行替换操作后的新字符串,按照空格进行分割,并打印输出分割后的字符列表。
# coding = utf-8 source_string = input() # 请在下面添加代码 ########## Begin ########## int_step1 = source_string.find('day') print(int_step1) source_string_step2 = source_string.replace('day','time') print(source_string_step2) source_string_step3 = source_string_step2.split(' ')#默认空格 print(source_string_step3) ########## End ##########
测试输入:
All day is no day when it is past.
预期输出:
4
All time is no time when it is past.
['All', 'time', 'is', 'no', 'time', 'when', 'it', 'is', 'past.']