常见的字符串操作

Python面面观

共 2413字,需浏览 5分钟

 · 2020-11-30

一部分字符串操作的总结,比较基础。目录:

  • 使用str.split() 切分数据

  • 将 datetime 类型转化为字符串类型

  • 字符串的合并操作

  • 使用 str.strip() 去除字符串前面和后面所有的字符串

  • 替代字符串中的某些字符串为另外的字符串

  • Python 中的 i++,i+

下面简单的演示。

使用 str.split() 切分数据

import pandas as pd
from pandas import Series,DataFrame
man = pd.DataFrame({
    'data':['张三|男','李四|男','王五|男']
})
man



# 使用str.split() 把数据分成两列
man = man['data'].apply(lambda x :Series(x.split('|')))
man




将 datetime 类型转化为字符串类型

# 将datetime类型转化为字符串类型
from datetime import datetime
stamp = datetime(2019,5,1)
stamp
datetime.datetime(2019, 5, 1, 0, 0)
str_stamp= str(stamp)
str_stamp
'2019-05-01 00:00:00'

字符串的合并操作

使用 join() 连接字符串数组

# join():连接字符串数组。将字符串、元组、列表、Series中的元素以指定的字符(分隔符)连接生成一个新的字符串
a=['1','2','3','4','5']
text = '  '.join(a)
text
'1  2  3  4  5'


使用 + 连接字符串

# 使用加号
x = 'a' + 'b'
x
'ab'


使用 format() 将多个字符串合并,主要用在变量输出上

x = 'i am {1} and {0} years old'.format(30.'Tony')
x
'i am Tony and 30.0 years old'


使用 Pandas 自带的 cat() 函数

#  Series.str.cat(others=None,  # 要合并的另外一个对象,如果为空则将左侧对象组合
#                 sep=None,     # 合并的分隔符,默认为空
#                 na_rep=None)  # 如果遇到NA值的处理方式,默认忽略

EG = pd.Series(['a''b''c']).str.cat(sep=';')
EG
'a;b;c'
EG = pd.Series(['a''b''c']).str.cat(['A''B''C'], sep='@@')
EG
0    a@@A
1    b@@B
2    c@@C
dtype: object


使用 str.strip() 去除字符串前面和后面所有的字符串

# str.strip([chars]);去除字符串前面和后面的所有设置的字符串,默认为空格
st = "   hello    "
st = st.strip()
print(st + 'word')
helloword
# 删除字符串'l, o'
st = st.strip('l, o')
print(st)
he


替代字符串中的某些字符串为另外的字符串

# str.replace(old, new[, max])
# old -- 将被替换的子字符串。
# new -- 新字符串,用于替换old子字符串。
# max -- 可选字符串, 替换不超过 max 次

st = "hello"
st = st.replace('l''a'1)
st
'healo'
# 替换字符串中的某些子串,可以用正则表达式来匹配被选子串。

# re.sub(pattern, repl, string, count=0, flags=0)
# pattern:表示正则表达式中的模式字符串;
# repl:被替换的字符串(既可以是字符串,也可以是函数);
# string:要被处理的,要被替换的字符串;
# count:匹配的次数, 默认是全部替换
import re

st = "hello 2019"
st = re.sub("([0-9]+)","word",st)
print(st)
hello word


Python 中的 i++,i+

顺便在这篇基础下面总结下 Python 中的 i++,i+ 这类写法和 Java 不一样。在新手入门时会有点疑问,这里列一下。

i+1

这种都是一样的写法,没什么问题,很好理解。

for i in range(3):
    i=i+1
    print(i)
1
2
3


i+

i+ 就是 Python 中的自增写法。相当于其他语言的 ++i。

for i in range(3):
    i+=5
    print(i)
5
6
7


i-

Python 中的自减写法。

for i in range(3):
    i-=5
    print(i)
-5
-4
-3


++i

Python 中的 ++i,仅仅是作为判断运算符号,类似数学中的负负得正。

# 体现在这个案例中,就是对结果值没影响
for i in range(3):
    ++i
    print(i)
0
1
2


i++

Python 中不支持这类写法,所以直接报错。

for i in range(3):
    i++
    print(i)
  File "", line 2
    i++
       ^
SyntaxError: invalid syntax
浏览 27
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报