Python Strings

1. Basic

#Python treats single quotes the same as double quotes.
var = 'haha'
var = "666"

  

2.  accessing

var = 'haha'
var[0] #'h'
var[1:3] #'ah'

  

3. Updating

We can update a string with a variable.

The variable can be a new string or some part of  the old string and new string.

var = '123'
var = var[:1]+'46'

  

4. Built-in string method

str = 'hello'
str.capitalize()  #It returns a copy of the string with only its first character capitalized.
#str = 'Hello

  

str = 'hello'
str.center(width, fillchar)  #The method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space.
#str.center(7, 6)
#str = '6hello6'

str.count(sub, start= 0,end=len(string))
#the method count() returns the number of occurrences of substring sub in the range [start, end].
#sub -- substring 
#start -- default is 0
#end

str.find(str, beg=0, end=len(string))
#Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.

str.isalnum() #Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. alphabetic+numeric

str.isalpha() #Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

str.isdigit() #Returns true if string contains only digits and false otherwise.

str.islower() #Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

str.isupper()

  

posted @ 2017-01-17 15:46  KennyRom  阅读(208)  评论(0编辑  收藏  举报