Home » Python » Python foundation -- using strings

Python foundation -- using strings

strings are immutable sequences,


>>>website = 'http://www.python.org'
>>>website[-3:] = 'com'
# error

string formatting -%

%, place a string on the left, and place the value that you want to format on the right:


>>>format = 'Hello,%s,%s, enough, for, ya,'
>>>values = ('world', 'hot')
>>>print format% values
Hello, world, hot, enough, for, ya,
?

if the string contains a percent sign, you need to use.

% per cent said
The s in

%s represents a string. If you want to retain three decimal digits when formatting floating-point numbers, you can use%.3f


The

tuple, as the parameter after%, uses parentheses


>>>'%s, plus,%s, equals,%s', % (1, 1, 2) 
'1 plus 1 equals 2'

field width and accuracy


The
# field width is 10, with an accuracy of 2
>>>%10.2f% pi
'3.14'

find method

Find the substring, return the index at the leftmost end of the substring, and return -1

if you don't find it
>>>'With, a, moo-moo, here, and, a, moo-moo, there'.find ('moo')
7
>>>'With, a, moo-moo, here, and, a, moo-moo, there'.find ('shit')
-1

join method

The inverse method of split must be string

to connect
>>>seq = ['1', '2', '3']
>>>sep = '+'
>>>seq.join (SEP)
'123+'

lower method

Returns string lowercase letter version


>>>'HELLO, worldD'.lower ()
Hello, world

replace method

Returns the string

obtained after all matches of a string have been replaced
>>>'This, is, a, test'.replace ('is', 'eez')
'Theez EEZ a test'

split method

Join's inverse method that separates strings into sequences


>>>'1+2+3+4+5'.split ('+')
['1', '2', '3', '4', '5']

strip method

Returns a string that removes the space on both sides. Note that the internal

is not included
>>>', internal, whitespace, is, kept,'.strip ()
'internal whitespace is kept'

translate method

Somewhat similar to the previous replace, but there are different.


first uses maketrans to complete a conversion table, and then calls the translate method


>>>from string import maketrans
>>>table = maketrans ('cs', 'kz')
>>>'this, is, an, incredible, test'.translate (table)
'thiz, IZ, an, inkredible, tezt'

is the C in the string to K, and s to z


Latest