目录

  • Python切片
  • * String字符串
  • * list列表
  • * 应用
  • Java截取字符串
  • * String
  • * 运用

Python切片

Python3切片——String字符串、list列表

参考链接:Python3 基本数据类型|菜鸟教程

* String字符串

  • 切片原理:
  • python 字符串切片获取最后两位 python3 字符串切片_字符串切片

  • 示例:
#!/usr/bin/python3
 
str = 'Hellowold'
 
print (str)          # 输出字符串
print (str[0:-1])    # 输出第一个到倒数第二个的所有字符
print (str[0])       # 输出字符串第一个字符
print (str[2:5])     # 输出从第三个开始到第五个的字符
print (str[2:])      # 输出从第三个开始的后的所有字符
print (str * 2)      # 输出字符串两次
print (str + "TEST") # 连接字符串
  • 输出结果:
Hellowold
Hellowol
H
llo
llowold
HellowoldHellowold
HellowoldTEST

* list列表

  • 原理:
  • python 字符串切片获取最后两位 python3 字符串切片_字符串_02

  • 示例:
#!/usr/bin/python3
 
list = [ 'abcd', 786 , 2.23, 'hello', 70.2 ]
tinylist = [123, 'hello']
 
print (list)            # 输出完整列表
print (list[0])         # 输出列表第一个元素
print (list[1:3])       # 从第二个开始输出到第三个元素
print (list[2:])        # 输出从第三个元素开始的所有元素
print (tinylist * 2)    # 输出两次列表
print (list + tinylist) # 连接列表
  • 输出结果:
['abcd', 786, 2.23, 'hello', 70.2]
abcd
[786, 2.23]
[2.23, 'hello', 70.2]
[123, 'hello', 123, 'hello']
['abcd', 786, 2.23, 'hello', 70.2, 123, 'hello']

* 应用

在之前一个项目中,现有如下命名文件夹(数字+英文);

python 字符串切片获取最后两位 python3 字符串切片_Python切片_03


现需要遍历根目录,获取所有英文名字,要求不显示第一个数字;

切片实现:name[1:]

import os
#1获取文件夹
folder_name = '/根目录'
sum = 1
#2获取文件夹中的文件名
file_names = os.listdir(folder_name)

os.chdir(folder_name)
for name in file_names:
    print(name[1:])
    sum += 1

输出:

wangyu
zhouwen
wulei
yyqx

python切片好用!!!!


这是分界线


Java截取字符串

* String

  • 原理:

Java 实例 - 删除字符串中的一个字符|菜鸟教程

  • 实例:
sql = "select * from 表 where id = 1 and name = wang and "
sql = sql.substring(0,sql.length()-4);//切去最后四个

输出:

sql = "select * from 表 where id = 1 and name = wang "

* 运用

处理sql语句and带来的报错 在之前一篇文章,是通过自定义SQL语句,遇到一个问题——当拼接字符串时,若采用一般方法:每个查找元素前面加上and,那么where后:最前面会多出一个and.

(1)简单处理方法是加一个附加条件(1=1)

python 字符串切片获取最后两位 python3 字符串切片_Python切片_04


python 字符串切片获取最后两位 python3 字符串切片_字符串切片_05


python 字符串切片获取最后两位 python3 字符串切片_字符串切片_06


问题:

上面的方法不影响sql语句查询,但是遇到插入、更新和删除时,就不能轻松应对了:

  • 因为不可能: insert into 表 where 1=1(id,name,password),语法错误
  • 也不可能 update 表 set 1=1 and id =1 and name =wang and password =123456 where 1=1 and id =1 ,语法错误
  • 更不可能:delete * from 表 where 1=1 and id =1,全删除了!!!

解决办法 切片:

sql = sql.substring(0,sql.length()-4);