Python Basic Learning-string

Source: Internet
Author: User

String Conversion Tool

The conversion of a single string can be made in the following ways

1.ord (), converts a string into ASCII code

2.CHR () to convert ASCII code to the corresponding character

Stringval = "H"
Print (ord (stringval)) #将单个字符串 "H" converted to->104
Print (Chr (104)) #将ACSII码 104 "H"

#为了生成一下个字符, you can pre-convert the current character into an orthopedic
s = ' 5 '
s = Chr (ord (s) + 1) #使用ord将5转成ACSII码, then +1, then acsii the code into the corresponding string by CHR
Print (s) #结果: 6
s = Chr (ord (s) + 1)
Print (s) #结果: 7

Print (Type (h)) #得到一个整数类型 <class ' int ' >
#配合一个循环语句去转换
B = ' 1101 '
I = 0
While B! = ":
I = i*2 + (ord (b[0))-Ord (' 0 '))
b = b[1:] #第一次循环后B变为101, second loop B becomes 01, B becomes 1 after the third loop, and fourth cycle B becomes ' empty string '
Print (i) #结果: I = 13


3. Convert a string to an integer by int ()

4. By str (), integers can be converted to strings

" 2 " Print # by the string "2"-> Integer 2

Modifying a string

String can not be modified in situ, once the attempt to modify in situ will be error

#原地修改字符串
Stringval = ' Hello '
Stringval[0] = "F" #打印结果报错 TypeError: ' str ' object does not the support item assignment

You can modify the string like this

1. Combine to assign a new string to the original variable name

2. Partitioning, indexing, assigning a new string to the original variable name

3. Pass the Replace () function-> assign a new string to the original variable name

4. By formatting format ()-> assigns a new string to the original variable name

#一, using the Merge method, modify the string ' spam '  'SPAM'print#spamspam
#二, modifying a string with the Shard \ Index method
Stringval = ' spamspam! '
Stringval = Stringval[:4] + ' JACK ' + stringval[-1]
Print (Stringval) # spamjack!

Python Basic Learning-string

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.