A summary of the language basics of Python (ii) loop and string manipulation

Source: Internet
Author: User

I. Loops and Branches

1. Conditional branching statements

If condition:

code block

Else

code block

2. While of the Loop statement

Think 1: Find the value of 1+2+3+....+10

  

sum =1 while num < 101    :+ = num    + = 1print(sum)

For loop

For statement:

code block

Second, string manipulation

1. Concatenation of strings

Use the plus sign to link

#字符串的链接, through "+'welcome' toGuangzhou'  + s2)

Use "," to link

S1 = ' Hello ' s2 = ' world ' Print (S1, S2) #使用 "," when linking, the position of "," will produce a space

Use% formatting links

' Hello '  'World'print ("%s%s"% (S1, S2))

Linking using the Join function

S1 = ['hello'' World']print ("" . Join (S1))

Note: the ". join* () function only needs to pass one parameter inside.

2. Repeating the output string

' Good '  3)

3. Get the characters in a string

#通过索引的方式实现 # Index: The number of characters in a string is numbered from 0, which also becomes the value range of the Subscript # index: [0, str.length-1' Good ' print (str3[0]) #索引值还可以从-1 start, 1 for theCountdown first character print (str3[-1])

4. Intercepting strings

#通过索引的方式实现 # Index: The number of characters in a string is numbered from 0, which also becomes the value range of the Subscript # index: [0, str.length-1'  Good'print (str3[0]) #索引值还可以从-1 start, 1 for the lastcharacter print (str3[- 1])

5. Determine if the specified character is included

" You is a good boy " Print ("good" in str4) #若包含有则返回True否则为False

6. Formatted output

#通过% to change the meaning of the following letters orsymbols, %% of " Lili "  45.5 print ("My name is%s, I am%d year old and my weight is%.2f kg
     c13>"%(name, age, Weight)) #注意:%.nf indicates the precision to n digits after the decimal point, rounding

Three, about the common function of string

1.eval (str)

Function: evaluates the string str as a valid expression and returns the result of the calculation. You can convert List,tuple,dict,set and string to each other.

>>>num1 = eval ('123')>>>Print (NUM1)123 >>>num2 = eval ("[1, 2, 3]")>>>Print (num2) [1  23]>>> num3 = eval ("12-3") >>> Print (num3)9

2.len (str)

Function: Returns the length of the current string (number of characters)

>>> Len ("you aregood")

3.str.lower ()

Function: Returns a string that turns uppercase letters in a string into lowercase letters

" Hello World ">>> print (str.lower ()) Hello World

4.str.upper ()

Function: Returns a string that converts a lowercase letter in a string to uppercase

" Hello World ">>> print (Str.upper ()) HELLO World

5.str.swapcase ()

Function: Returns a string that turns uppercase letters in a string into lowercase letters and lowercase letters to uppercase (string case inversion)

" Hello World ">>> print (Str.swapcase ()) HELLO World

6.str.capitalize ()

Function: Returns a first-letter uppercase, other lowercase string

" Hello World ">>> print (Str.capitalize ()) Hello World

7.str.title ()

Function: Returns a string with the first letter of each word capitalized

" Hello World ">>> print (Str.title ()) Hello World

8.str.center (Width[,fillchar])

Function: Returns a centered string of the specified width, fillchar as a fill character

" Hello World ">>> print (Str.center ("*"))****************** *hello world********************

9.str.ljust (Width[,fillchar])

Function: Returns a left-aligned string of the specified width, fillchar as a fill character. Use space padding by default

" Hello World ">>> print (str.ljust ("*")) HelloWorld ********* ******************************

  

10.str.rjust (Width[,fillchar])

Function: Returns a left-aligned string of the specified width, fillchar as a fill character. Use space padding by default

" Hello World ">>> print (str.rjust ("*"))******************* Hello World

11.str.zfill (width)

Function: Returns a length of width string, the original string right-aligned, the front complement 0

" Hello World ">>> print (Str.zfill) 000000000000000000000000000000000000000Hello World 

12.str.count (str[, Strat][,end])

Function: Returns the number of occurrences of STR in a string, optionally specifying a range that, if not specified, is case-sensitive by default.

" Hello World ">>> print (Str.count ("hello"0))0 

13.str.find (Str1[,start],[,end])

Function: From left to right to detect whether the STR1 string contains a string, you can specify a range, by default from beginning to end.

Return is the first occurrence of the subscript, if not queried, then return-1

" Hello World " " Llo " 0 Ten ))2

14.str.rfind (Str1[,start][,end])

Function: Similar to Str.find (), but from the right to start looking

" Hello World " " Llo " 0 Ten ))2

15.str.index (str1[strat=0],[end = Len (str)])

function is similar to find (), unlike find (), if STR1 does not exist, it will report an exception

" Hello World " " Hello " 0 Ten )) valueerror:substring not found

16.str.lstrip ()

Function: Truncate the string specified on the left side of the strings, by default removing whitespace characters (including ' \ n ', ' \ R ', ' \ t ', ')

' * * * * very good '>>> print (Str.lstrip ())>>> print (Str.lstrip ())* * * * * * * are very Good>>> print (Str.lstrip ("*")) Very good

17,str.rstrip ()

Function: Truncate the string specified to the right of the strings, the default is to remove the white space character (including ' \ n ', ' \ R ', ' \ t ', ')

' * * * * good**** '>>> print (Str.rstrip ()* * * * * * good****>>> print (Str.rstrip (" * " )* * * * are good

18.str.strip ()

Function: Truncate the strings specified on both sides of the string, then the default is to remove the white space character (including ' \ n ', ' \ R ', ' \ t ', ')

" Hello World">>> str1.strip ()'Hello World        '

19.string.split (str = ", Num=string.count (str))

Function: Slice string with the str divider, and if NUM has a specified value, only the NUM substring is split

The str--delimiter, which defaults to all empty characters, including spaces, line breaks (\ n), tab characters (\ t), and so on. num--split Times

>>> str1 ="Hello you is good">>>str1.split () ['Hello',' You',' is','Good']>>> Str1.split (" ",2)['Hello',' You','is good']

Practice:

1. Calculate thenumber of all the numbers that can be divisible by 3 or 17 within 1~ 100 and 2. Calculates the numberof daffodils in 100-999.  3. CalculateThe number of numbers that can be divisible by 7, but not even, within 200~ 500.  4"one-time   Input"--"one-time investment"  --The lottery--"winning/not winning-"user input Continue " Automatically exits the game "5" when the balance is 0. Hundred money to buy hundred chickens, existing 100 text money, Rooster 5 text Money A, hen 3 text money A, chicken a text money 3 only, Request: Rooster, hen, chicken to have, buy 100 chickens, put 100 of money spent, buy chicken is an integer. How many cocks, how many hens how many chickens?

  

  

A summary of the language basics of Python (ii) loop and string manipulation

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.