首页 > 编程语言 >Python字符串与数组相互转换

Python字符串与数组相互转换

时间:2022-10-22 09:57:14浏览次数:57  
标签:boy good join str Python print doiido 数组 字符串

Python中有join()和os.path.join()两个函数,

具体作用如下:

  1. join(): 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
  2. os.path.join(): 将多个路径组合后返回,语法: os.path.join(path1[,path2[,…]])

1. 字符串转数组

str = '1,2,3,4,5,6'
arr = str.split(',')
print arr 
#对序列进行操作(分别使用' '与':'作为分隔符)
 
>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido

#对字符串进行操作
>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
 
 
#对元组进行操作
>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido
 
 
#对字典进行操作
>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello

#合并目录
>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'

2. 数组转字符串

#方法1
arr = ['a','b']
str1 = ','.join(arr)
print str1
# 输出结果: a,b
#方法2
arr = [1,2,3]
#str = ','.join(str(i) for i in arr)#此处str命名与str函数冲突!
str2 = ','.join(str(i) for i in arr)
print str2
# 输出结果: 1,2,3

3. 清除字符串前后空格函数的方法

str = '  2014-04-21 14:10:18  '
str2 = str.strip()
str3 = re.sub(' ','',str)
  
print str2
print str3
结果如下:
>2014-04-21 14:10:18
>2014-04-2114:10:18

标签:boy,good,join,str,Python,print,doiido,数组,字符串
From: https://www.cnblogs.com/java-six/p/16815371.html

相关文章

  • Golang 和 Python 随机生成N位字符串
    Golang:funcRandomString(nint)string{ varletters=[]byte("ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789") result:=make([]byte,n) /......
  • 模板字符串
    模板字符串在ES5当中,当需要把多个字符串和多个变量拼接至一起时,写法相当的复杂varname="狗蛋",age=12,gender="男生"varstr="大家好,我是"+name+",今年"+age+"岁了,......
  • Python: Facade Pattern
    DuFacade.pyimportosimportreimportthreading#外观模式FacadePatternclass_IgnitionSystem(object):@staticmethoddefproduce_spark():......
  • Python学习三天计划-2
    一、函数函数:是组织好的,可重复使用的,用来实现特定功能的代码段。优点:可供重复利用的代码段提高程序的复用性减少重复性代码提高开发效率1.定义deffunc1():......
  • Python程序员常犯的编码错误(二)
    1.引言本文是Python程序员常犯的编码错误的第二篇,在上一篇中我们重点介绍了常见的五种错误,本文继续介绍该话题,希望大家在日常生活中多多关注。闲话少说,我们直接开始吧!2.......
  • Python: Decorator Pattern
     DuDecorator.py#装饰模式DecoratorPatternimportsix#https://pypi.org/project/six/[email protected]_metaclass(ABCMeta)classAbstra......
  • 每日算法2:翻转字符串
    题目描述:判断字符串中重复次数最多的字符//解决思路://1.判断字符重复的方法//创建空数组,利用键值对形式对每个字符进行计数//用到采用for循环结合if判断对象......
  • Selenium+Python系列(三) - 常见浏览器操作
    写在前面上篇文章为大家分享了自动化测试中,常见元素定位的操作。今天再次读文章,居然忘记了大家特别喜欢的CSS和Xpath定位操作分享,这怎么能行呢?马上安利,感兴趣的同学去参......
  • js统计字符串每个字符出现的次数
    统计下面字符串中每个字符出现的频率letstr="fgasdfadfdasd"letresult={}for(leti=0;i<[...str].length;i++){if(!result[[...str][i]]){res......
  • Python RabbitMQ pika的安装及work消息模型的使用
    RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件,RabbitMQ服务器是用Erlang语言编写的,而集群和故障转移是构建在开放电信平台框架上的。所有主要的编程语言均有......