Python字元處理

來源:互聯網
上載者:User

標籤:java   int   str   name   lan   合并   hello   刪除   開頭   

字串就是一系列字元。在python中,用引號括起來的都是字串,這裡的引號可以是單引號也可以雙引號。

例如:

>>> ‘this is a string‘ 
‘this is a string‘
>>> “this is also a string”
“this is also a string”

 

對字串的操作:

 

#修改字串的大小寫#

1、修改單詞首字元

>>> name=‘alben xue‘
>>> type(name)
<class ‘str‘>
>>> print(name.title())
Alben Xue

title()跟在變數後面,使用.串連,代表通過title()定義的方法對變數name進行處理

2,修改所有字元

>>> name
‘alben xue‘
>>> print(name.upper())
ALBEN XUE
>>> print(name.lower())
alben xue

#合并字串#

 

在python中,通過“+”進行字串合并

舉例:

>>> first_name=‘xue‘
>>> last_name=‘lingming‘
>>> full_name=first_name+last_name
>>> message=‘hello,‘+full_name.upper()+"!"
>>> print(message)
hello,XUELINGMING!

     “上述代碼,把一串字串儲存到變數中,後續所有操作對變數執行,這樣會顯得更加方便”

#使用定位字元或分行符號來添加空白#

在編程種,空白泛指任何非列印字元、如空格、定位字元、分行符號。

1、使用定位字元

>>> print(‘python‘)
python
>>> print(‘\tpython‘)
             python

2、使用分行符號

>>> print(‘python\C##\nPHP\nJavaScript‘)
python\C##
PHP
JavaScript

3、定位字元與分行符號共同使用

>>> print(‘Languages:\n\tPython\n\tC##\n\tPHP‘)
Languages:
              Python
              C##
              PHP

#刪除多餘的空白符#

>>> favorite_language=‘python ‘
>>> favorite_language
‘python ‘

可以看到這個變數中有一個空格,對於程式而言是能識別的,對個個人而言是多餘的,如何刪除

>>> favorite_language.rstrip()
‘python‘

這隻是臨時的,要想永久的刪除空白,需要把這個字串儲存到變數中

>>> favorite_language=favorite_language.rstrip()
>>> favorite_language
‘python‘

剔除字串開頭的字元

>>> name=‘ alben ‘
>>> name
‘ alben ‘
>>> name.lstrip()    #去頭#
‘alben ‘
>>> name.rstrip()   #去尾#
‘ alben‘
>>> name.strip()    #去頭去尾#
‘alben‘

 P

Python字元處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.