趣學python第3章字串2把值插入到某位置

2021-08-14 20:49:44 字數 1420 閱讀 4889

趣學python第3章字串2把值插入到某位置

1.用%s把值嵌入到字串裡

mysorce = 100

message = 'i scored %s point.'

print(message % mysorce)

********************= restart: c:/python27/lianxi/31.py ********************=

i scored 100 point.

對於同乙個%s佔位符可以用不同的變數來穿給它不同的值。

#!usr/bin/env python

#coding:utf-8

mysorce = 100

mysorce2 = 99

message = 'i scored %s point in %s'

kemu1 = '語文'

kemu2 = '數學'

print(message % (mysorce ,kemu1))

print(message % (mysorce2 ,kemu2))

執行結果

********************= restart: c:/python27/lianxi/31.py ********************=

i scored 100 point in 語文

i scored 99 point in 數學

用括號將多個替換的變數括起來,值排放的順序就是它們在字元中被引用到的順序。

2.字串乘法

spaces = ' '*25

print('%s 12 butts wynd' % spaces)

********************= restart: c:/python27/lianxi/31.py ********************=

12 butts wynd

乘法用*,小鍵盤上的星花標記。

low = 12

fr =11

pay =low * fr

fred = "i should pay for %s"

print (fred *2)

space = ' '*25

print ('%s 12 butts wynd '% space)

print ('%s twinklebottom hesth' % space)

print (pay)

print ()

print ('dear sir' )

print ()

print ('%s twinkle bottom hesth' % space)

變數的乘法沒有什麼不同,這裡重要的是字串的乘法,它可以讓字串複製。

趣學PYTHON第3章 字串

字串的使用,可以是英文單引號,雙引號,都可以輸出 1.但是當字串超過了一行,就要使用三個單引號了。否則會報錯。三個單引號可以解決這個問題,eol while scanning string literal 2.引號用來標註字串,但是如果輸出的字串也包含引號,怎麼辦。silly string he s...

趣學python第7章函式

趣學python第7章函式 函式的組成部分三個,函式名,引數,函式體 def testfunc name print hello,s name testfunc wang 列印出hello,wang restart c python27 lianxi 2018123.py hello,wang de...

趣學python第7章使用模組

趣學python第7章使用模組 1.time模組 import time 引入時間模組 print time.time restart c python27 lianxi 2018123.py 1517052225.95 列印出一串數字 更改列印函式,print time.asctime sat j...