網站首頁 編程語言 正文
一、split()函數的簡單應用
1.join()函數
Python join() 方法用于將序列中的元素以指定的字符連接生成一個新的字符串。
join()函數是 split() 方法的逆方法,用來將列表(或元組)中包含的多個字符串連接成一個字符串。
newstr=str.join(sequence)
newstr – 表示合并后生成的新字符串
sequence – 要連接的元素序列,必須為可迭代對象。
返回通過指定字符連接序列中元素后生成的新字符串。
舉例如下:
將元組中的字符串合并成一個字符串:
寫法1:
>>> symbol="-" # 連接符
>>> seq=("I","love","China") # 字符串序列
>>> symbol.join(seq)
'I-love-China'
寫法2:省略對連接符號的定義,直接用
>>> seq=("I","love","China")
>>> '-'.join(seq)
'I-love-China'
>>>
將列表中的字符串合并成一個字符串:
>>> list=["I","love","China"]
>>> '-'.join(list)
'I-love-China'
>>>
將字典中的鍵值進行連接:
>>> dict1={"a:1","b:2","c:3","d:4"}
>>> "-".join(dict1)
'c:3-d:4-b:2-a:1'
>>>
PS:python中strip的使用
今天聊聊python去除字符串空格的函數:strip()和replace()
1.strip():
函數功能描述:Python strip() 方法用于移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。
注意:該方法只能刪除開頭或是結尾的字符,不能刪除中間部分的字符。
格式:str.strip([char])。其中,str為待處理的字符,char指定去除的源字符串首尾的字符。
返回結果:去除空格時候的新字符串。
示例:
str = "00000003210Runoob01230000000"
print str.strip( '0' ) # 去除首尾字符 0
結果:3210Runoob0123
str2 = " Runoob " # 去除首尾空格
print str2.strip()
結果:Runoob
2.replace()
函數功能描述:Python replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數max,則替換不超過 max 次
格式:str.replace(old, new[, max]),參數在函數功能描述中已經說明。
返回值:返回字符串中的 old(舊字符串) 替換成 new(新字符串)后生成的新字符串,如果指定第三個參數max,則替換不超過 max 次。
示例:
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)
結果:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
同樣可以采用replace實現空格的去除。舉個例:
" x y z ".replace(' ', '') # returns "xyz"
原文鏈接:https://blog.csdn.net/qq_44985415/article/details/128702838
相關推薦
- 2022-07-19 react組件通訊的三種方式props:父組件和子組件互相通訊、兄弟組件通訊
- 2022-11-06 SQL?Server?Reporting?Services?匿名登錄的問題及解決方案_MsSql
- 2022-07-31 Python如何生成隨機數及random隨機數模塊應用_python
- 2024-03-01 解決 “TypeError: Cannot read properties of undefined
- 2022-07-21 數據庫慢查詢介紹并優化
- 2022-10-20 C#?Random類隨機函數實例詳解_C#教程
- 2023-03-15 pandas創建DataFrame對象失敗的解決方法_python
- 2022-12-24 C#?Math中常用數學運算的示例詳解_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支