& Lt; Basic Python tutorial & gt; learning notes | Chapter 1 | string, python Chapter 2

Source: Internet
Author: User
Tags pears print format

<Basic Python tutorial> learning notes | chapter 03rd | character string and python chapter 03rd

Chapter 2: Using strings

------

Supported operations

  • Index
  • Slice
  • Add Element
  • Delete Element
  • New Element
  • Search for elements (check whether an element is a member of a sequence)
  • Sequence length
  • Maximum Value
  • Minimum value
  • Other built-in functions
>>> Website = 'HTTP: // www.python.org '>>> website [-3:] = 'com' # this operation is invalid because the string remains unchanged, traceback (most recent call last) cannot be modified: File "<pyshell #162>", line 1, in <module> website [-3:] = 'com 'TypeError: 'str' object does not support item assignment
------

String formatting:
% S: conversion specifier ancestor

# Stable type> str1 = "Hello, % s. % s enough for you ya? ">>> Val1 = ('Jerry ', 'hot') >>> print str1 % val1Hello, Jerry. Hot enough for you ya? # Floating point type> format = "PI with three decimals: %. 3f ">>> from math import pi >>> print format % piPI with three decimals: 3.142 Note: 1. if a list is used, the sequence is understood as a value. Only the ancestor and dictionary can format more than one value. percent: % Template string # similar to replacing variables in linux, Template, substitute (convert passed parameters) >>> s = Template ('$ x, glorious $ x! ') >>> S. substitute (x = 'slurm')' slurm, glorous slurm! '# If it is part of a word, enclose it with {}> s = Template (' I love $ {x} rry! ') >>> S. substitute (x = 'she')' I love Sherry! '# If it is a dollar, pay attention to the $ symbol, safe_substitute does not report errors due to missing values or dollar signs >>> s = Template ('using $ buy $ {x }! ') >>> S. substitute (x = 'food')' Using $ buy food! '# Use the dictionary to provide key/value pairs >>> s = Template ('A $ thing must never $ Action') >>> d = {}>>> d ['action'] = 'gentleman '>>> d ['action'] = 'show his socks' >>> s. substitute (d) 'A gentleman must never show his socks '>>> s = Template (' I am $ {name}, $ {age} years old. ') >>> d = {'name': 'Jerry', 'age': 50 }>>> s. substitute (d) 'I am Jerry, 50 years old. '#>>> s =' % s plus % s equals % s' % (, 2) >>> print s1 plus 1 equals 2
------

Basic conversion specifiers:

(1) % characters, marking the start of conversion
(2) Conversion mark (optional)

  • -Left alignment
  • + Positive and negative signs before the conversion value
  • "" Blank character, indicating that space is reserved before a positive number
  • If the value of 0 is not enough, fill it with 0.
(3) Minimum field width (optional ):
  • Minimum width with a specified value
  • If it is *, the value is read from the ancestor.
(4). Precision value (optional)
  • If it is a real number, the precision value indicates the number of digits following it.
  • If it is a character, the precision value indicates the maximum width
  • If it is *, the precision value is read from the ancestor.
(5) Conversion Type


------

Simple Conversion

>>> print 'price of eggs is %d' % 12price of eggs is 12>>> print 'Hexadecimal price of eggs: %x' % 42Hexadecimal price of eggs: 2a>>> from math import pi>>> 'Pi: %f...' % piPi: 3.141593...>>> 'very inexact estimate of pi: %i' % pivery inexact estimate of pi: 3>>> 'Using str: %s' % 42LUsing str: 42>>> 'Using repr: %r' % 42LUsing repr: 42L
------

Field width and precision

Both parameters are integers separated by.. If only the precision is given, it must contain a vertex number.

>>> '% 10f' % pi # The width is 10' 3.141593' >>>' % 10.2f '% pi # The width is 10, the precision is 2 '000000'> '%. 2f '% pi # The precision is 2' 3. 14'> '%. 5s '%' Hello, world! '# String Length 'hello' >>>' %. * s' % (5, 'Hello, World! ') # String Length, whose value reads 'hello' from the ancestor'
------

Symbol, alignment, and 0 Filling

Before the field width and precision value, you can place a "standard table", which can be 0, +, "" >>>' % 010.2f '% pi # width is 10, accuracy 2, fill '100% with 0. 14' >>> 0108 >>>>' %-10.2f '% pi # Left alignment' 3. 14' # space. It is useful when the value is positive or negative> print ('% 5d' % 10) + '\ n' + (' % 5d '%-10) 10-10 # +, indicating whether it is a positive number or a negative number, marking its positive and negative value, useful in alignment> print ('% + 5d' % 10) + '\ n' + (' % + 5d '%-10) + 10-10

String format example

width = input('Enter number here:')price_width   = 10item_width    = width - price_widthheader_format   = '%-*s%*s'content_format  = '%-*s%*.2f'print '='*widthprint header_format  % (item_width,'Item',price_width,'Price')print '-'*widthprint content_format % (item_width,'Apples',price_width,0.4)print content_format % (item_width,'Pears',price_width,0.5)print content_format % (item_width,'Banana',price_width,8)print content_format % (item_width,'Tomato',price_width,6)print '='*width
Output result: Enter number here: 40 ============================================== = Item Price -------------------------------------- Apples 0.40 Pears 0.50 Banana 8.00 Tomato 6.00 ==================== ================

------

String Method

Find: Search for characters in a long string, and return the leftmost index position. The first position is 0, and not found as-1.

# Find does not return a Boolean value:-1: 0 not found: Found, index is 0, that is, the start position >>> 'I love python '. find ('perl ')-1 >>>' I Love python '. find ('python') 7 >>> title = 'python is so funny language' # If the searched object is in the starting position, it is 0 >>> title. find ('python') 0 # If there are multiple, return the first matched index value >>> title. find ('O') 4 # This method can select the start point, end point> subject = '$ Get rich now !!! $ '# Search from 0 by default >>> subject. find ('$') 0 # Only the starting position is provided> subject. find ('$', 1) 20 # provides the start position and end point> subject. find ('!!! ', 0, 16)-1
------

Join: Anti-split method, used to add elements to the queue

>>> Seq = [1, 2, 3, 4, 5] # Number list >>>> sep = '+' >>> sep. join (seq) Traceback (most recent call last): File "<pyshell #242>", line 1, in <module> sep. join (seq) TypeError: sequence item 0: expected string, int found >>> seq = ['1', '2', '3', '4 ', '5'] # string list >>> sep. join (seq) '1 + 2 + 3 + 4 + 5'> dirs = '', 'usr', 'bin ', 'env' # note the leading space >>> '/'. join (dirs) '/usr/bin/env'> print 'C: '+ '\\'. join (dirs) # Double backslash C: \ usr \ bin \ env

------

Lower: Convert all strings to lowercase letters.

>>> 'Hello, world '. lower () 'Hello, world' # if the input is in uppercase, the value cannot be found >>> if 'Jerry 'in ['Jerry', 'Tom ', 'sherry', 'john']: print "Found it. "# in this case, convert it to lower case >>> if 'Jerry '. lower () in ['Jerry ', 'Tom', 'sherry', 'john']: print "Found it. "Found it.
# Title (): Upper letter >>> "This is a dog, that's a pig ". title () "This Is A Dog, That's A Pig" # capwords () in the string module can also enable the upper letter function >>> import string >>> string. capwords ('hello, world. ') 'Hello, world.'

------

Replace: replace all after finding

>>> 'Tom and Jerry'.replace('Tom','Sherry')'Sherry and Jerry'

------

Split: A very important method, the reverse method of join

>>> '1 + 2 + 3 + 4 + 5 '. split ('+') ['1', '2', '3', '4 ', '5'] >>> '/usr/bin/env/python '. split ('/') ['', 'usr', 'bin', 'env', 'python'] # If no Delimiter is provided, use a space, create a table and use line breaks to separate them >>> 'Using the default '. split () ['using', ''the, 'default']
------

Strip: Removes the null characters on both sides of the string, excluding the character strings.

>>> 'How old are you? '. Strip ()' How old are you? '# If the input may contain spaces, use it with strip () >>> names = ['Jerry', 'sherry ', 'Tom '] >>> name = 'Jerry' >>> if name in names: print 'Find it. '>>> if name. strip () in names: print 'Find it. 'Find it.
# You can also specify the items to be removed. For example, if it is local, It is (remove the first micro-ends *!) >>> '*** Spam ** in * everyone !!! * ** ''' ** Spam * in * everyone !!! * ** '>' ** Spam * in * everyone !!! * ** '. Strip ('*! ') 'Spam * in * everyone'

------

Translate: The same as replace, which can replace some parts of the string. Difference: translate only processes a single character.

Advantage: Multiple Replicas can be performed at the same time. Sometimes it is more efficient than replace. You need to prepare a conversion table before conversion.

>>> From string import maketrans # used in combination with maketrans >>> table = maketrans ('cs ', 'kz') # Use k to replace c, replace s with z> 'this is c character '. translate (table) 'thiz iz k kharakter'
------

Functions in this Chapter

String. capwords (s [, sep]) use the split function to split the string and use capitalize to uppercase the first letter of each word;
The join function uses the sep as the separator to connect words.
String. maketrans (from, to) create a table for conversion



What is a string?

In vb
Dim str as string 'declares a string
Str = "231dd &" '231dd & is the content, and str is the variable name.
In C
Char s [] = {""}; // you can define an empty string as a variable s array.
S [1] = 'a'; // the first character is a. Note that single quotation marks are used here.
S [2] = '\ 0'; // string end

Character and string are different

Character is defined in the database
String is defined in programming languages.
For example, String str = 'Tom ';
In the database, the table has a field name that defines the character type, so str can be stored in this field of this table.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.