Top 40 common operations of Python string

Time:2020-11-20

The first official account is CoderMrWu. We share high-quality technology articles and experiences every week. Welcome everyone to pay attention to and share with you.

Today, I read an article and summarized the common syntax of 40 Python string types. I feel it is very interesting. I’d like to share it with you. Although you may not be able to use some grammar, it is also a kind of ingenious skill.

1 / create string

s1 = 'This is a test.'

2 / use the print statement to view the output

# python3/python2
>>> print('this is a test.')
this is a test.
# python3/python2
>>> print ('test')
test
# python2
>>> print '123'
123

3 / single line view output

>>> s1 = 'this is'
>>> s2 = ' a test'
>>> print(s1+s2)
this is a test

4 / single line n view output

>>> print(s1+'\n'+s2)
this is
 a test

5 / String subscript notation

>>> print(s1[0])
t
>>> print(s1[1])
h
>>> print(s1[8])
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: string index out of range

6 / subscript string addition

>>> print(s1[1]+s1[3]+s1[4])
hs

7 / slice string

>>> print(s1[0:5])
this
>>> print(s1[0:])
this is
>>> print(s1[:])
this is
>>> print(s1[:-1])
this i
>>> print(s1[::2])
ti s

8 / negative index slice

>>> print(s1[-5:-1])
is i
>>>Print (S1 [- 1:: - 1]) reverses the string
si siht

% 9 / format operator

>>> print('this is a %s' % 'test')
this is a test
>>> print('this is a %(test)s' % {'test':'12345'})
this is a 12345

10 /% with integer

>>> print('1+1 = %(num)01d' % {'num': 2})
1+1 = 2
>>> print('1+1 = %(num)02d' % {'num': 2})
1+1 = 02
>>> print('1+1 = %(num)03d' % {'num': 2})
1+1 = 002

11 /% for stations

>>> print( '%(a)s %(n)03d - program is the best.' % {'a':'Python','n':3})
Python 003 - program is the best.

12 / utilization\nSplit string

>>> print(' %(a)s %(n)03d - program is the best \n %(a)s helped me understand programming.' % {"a":"Python","n":3})
Python 003 - program is the best
Python helped me understand programming.

13 / multiple\n

>>> print(' I love %(a)s. \n I like %(b)s. \n I like to %(c)s. \n my %(d)s is %(num)03d.'%{"a":"to code","b":"ice-cream","c":"travel","d":"age","num":32})
I love to code.
I like ice-cream.
I like to travel.
my age is 032.

Use of% 14

>>> print('Hello everyone I am using Python %d.7 version.' % 3.7)
Hello everyone I am using Python 3.7 version.

>>> print('%s %s %d %d %f %f' % ('Hercules', 'Zeus', 100, 20, 3.2, 1))
Hercules Zeus 100 20 3.200000 1.000000

>>> print('This is a +%d integer' % 10)
This is a +10 integer

>>> print('This is a negative -%d integer' % 250)
This is a negative -250 integer

>>> print('This is a confused -%d integer' % 300)
This is a confused -300 integer

15 / string to integer

>>> s3 = '123'
>>>Print (10 * int (S3)) ා multiplication
1230
>>>Print (10 * S3) × multiple
123123123123123123123123123123
>>> print('1'+'45')
145

>>> print('1'+45)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str


>>> print(float('1')+float('45'))
46.0

16 / gets the number of times a single character appears in a string

>>> text = 'this is a test.'
>>> print(text.count('t'))
3
>>> print(text.count('is'))
2

17 / capitalize string

>>> text = 'this is a test.'
>>> print(text.upper())
THIS IS A TEST.

18 / make string lowercase

>>> text = 'THIS IS A TEST.'
>>> print(text.upper())
this is a test.

19 / combined string

>>> ' '.join(text)
't h i s   i s   a   t e s t .'

>>> ','.join(['hello', 'Dean'])
'hello,Dean'

20 / split string

>>> text = 'this is a test.'
>>> print(text.split(' '))
['this', 'is', 'a', 'test.']

21 / determines whether the string is uppercase

>>> text
'this is a test.'
>>> up_text = text.upper()
>>> print(up_text.isupper())
True

22 / determines whether the string is lowercase

>>> low_text = text.lower()
>>> print(low_text.islower())
True

23 / judge whether the string is composed of alphanumeric characters

>>> text1 = 'Lession 01'
>>> print(text1.isalnum())
False
>>> text2 = 'Lession01'
>>> print(text2.isalnum())
True

24 / gets the length of the string

>>> text
'this is a test.'
>>> print(len(text))
15

25 / converts a string into an asscii code in base 10

>>> print(ord('A'))
65
>>> print(ord('B'))
66
>>> print(ord('a'))
97
>>> print(ord('b'))
98

26 / converts the decimal assii code into a string

>>> print(chr(65))
A
>>> print(chr(42))
*
>>> print(chr(118))
v
>>> print(chr(60))
<

27 / escape character

>>> print('What\'s up?')
What's up?

>>> # the apostrophe is not needed in this case.
>>> print("What's up?")
What's up?

>>> # the apostrophe is needed to add on the quotes to the text
>>> print("\"What's up?\"")
"What's up?"

>>> # triple quotes can escape single, double, and a lot more.
>>> print("""What's up? Does the "" need an escape?""")
What's up? Does the "" need an escape?

28 / format strings with commas

>>>Print ('Here are ', 10,' Apples')
Here are 10 apples

29 / format format string

>>> text
'this is a test.'
>>> print('This is a {}'.format(text))
This is a this is a test.
>>> print('Number {1} and number {0}'.format(100, 200))  # keyword position
Number 200 and number 100

Passing characters by name in 30 / format

>>>Print ('Here are {num} types}. '. Format (Num = 10, type ='apple'))
Here are 10 apples.
>>>TMP = {'num': 10, 'type':'apple '}
>>>Print ('Here are {num} types}. '.format(**tmp))
Here are 10 apples.

31 / format passing characters in parameter order

>>>Print ('Here are {1} and {0}. '. Format ('apple', 10))
Here are 10 apples.

Accessing object properties in 32 / format

>>> class Rectangle:
 def __init__(self, length, width):
  self.length = length
  self.width = width
 def __str__(self):
  return 'Rectangle({self.length}, {self.width})'.format(self=self)


>>> rect = Rectangle(10, 5.5)
>>> print(rect.__str__())
Rectangle(10, 5.5)

33 / align text

>>> print('{:<10}'.format('X')) # left align
X
>>> print('{:>10}'.format('X')) # right align
         X
>>> print('{:^10}'.format('X')) # center
    X
>>> print('{:?^10}'.format('X')) # add a fill character
????X?????

34 / format binary, octal and hexadecimal

>>> print('Binary number: {0:b}'.format(50))
Binary number: 110010

>>> print('Octal number: {0:o}'.format(100))
Octal number: 144

>>> print('Hexadecimal number: {0:x}'.format(2555))
Hexadecimal number: 9fb

35 / use comma as separator

>>> print('{:,}'.format(2783727282727))
2,783,727,282,727

>>> print('{:.2%}'.format(90.60/100))
90.60%

36 / usefTo format a string

>>> item_1, item_2, item_3 = 'computer', 'mouse', 'browser'

>>> print(f"He uses a {item_1}.")
He uses a computer.

>>> print(f"He uses a {item_2} and a {item_3}.")
He uses a mouse and a browser.

>>> print(f"He uses a {item_1} 3 times a day.")
He uses a computer 3 times a day.

37 / format string with template

# docs: https://docs.python.org/3/library/string.html#template-strings
>>> from string import Template
>>> poem = Template('$x are red and $y are blue')

>>> print(poem.substitute(x='roses', y='violets'))
roses are red and violets are blue

38 / traversal of string

>>> text
'this is a test.'
>>> for item in text:
...     print(item)
...
t
h
i
s

i
s

a

t
e
s
t
.

39 / use while loop

>>> i = 0
>>> while i < len(text):
        print(text[i])

40 / save string in three quotation marks

>>> def triple_quote_docs():
 """
 In the golden lightning
 Of the sunken sun,
 O'er which clouds are bright'ning,
 Thou dost float and run,
 Like an unbodied joy whose race is just begun.
 """
 return

>>> print(triple_quote_docs.__doc__)

 In the golden lightning
 Of the sunken sun,
 O'er which clouds are bright'ning,
 Thou dost float and run,
 Like an unbodied joy whose race is just begun.

>>>

reference resources:

Recommended Today

Summary of recent use of gin

Recently, a new project is developed by using gin. Some problems are encountered in the process. To sum up, as a note, I hope it can help you. Cross domain problems Middleware: func Cors() gin.HandlerFunc { return func(c *gin.Context) { //Here you can use * or the domain name you specify c.Header(“Access-Control-Allow-Origin”, “*”) //Allow header […]