Python 程序形成一个新字符串,该字符串由给定字符串中的前 2 个和后 2 个字符组成
当需要形成一个由给定字符串中的前两个和后两个字符组成的新字符串时,可以定义一个计数器,并可以使用索引来访问特定范围的元素。
以下是同一演示:
示例
my_string = "Hi there how are you"
my_counter = 0
for i in my_string:
my_counter = my_counter + 1
new_string = my_string[0:2] + my_string [my_counter - 2: my_counter ]
print("The string is ")
print(my_string)
print("The new string is ")
print(new_string)输出
The string is Hi there how are you The new string is Hiou
说明
定义一个字符串并将其显示在控制台上。
一个计数器初始化为 0。
遍历字符串,并使用索引访问前 2 个和后两个元素。
将其分配给变量。
它是显示在控制台上的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP