《python无师自通》第六章

格式化

大括号可以替换成其他

>>> "willian {}".format("good")
'willian good'
n1 = input("请输入名词:")
v = input("请输入动词:")
adj = input("请输入形容词:")
adv = input("请输入副词:")

r = """这个{}{}到{}还有{}
    """.format(n1,v,adj,adv)
print(r)

请输入名词:猴子
请输入动词:打
请输入形容词:疯狂
请输入副词:肆意地
这个猴子打到疯狂还有肆意地

分割split()

>>> "好无聊啊,好像被分割".split(",")
['好无聊啊', '好像被分割']

连接join()

>>> a = "手拉手"
>>> result = "+".join(a)
>>> result
'手+拉+手'

去除空格strip()

>>> "   这   ".strip()
'这'

挑战练习

1.打印字符串"Camus"中的所有字符。

print(("\n").join ("Camus"))

2.编写程序,从用户处获取两个字符串,将其插入字符串"Yesterday I wrote
a [用户输入 1]. I sent it to [用户输入 2]!"中,并打印新字符串。

a = input("请输入a:")
b = input("请输入b:")
line1 = "Yesterday I wrote a {}. I sent it to {}".format(a,b)
print(line1)

3.想办法将字符串"aldous Huxley was born in 1894."的第一个字符大写,
从而使语法正确。

str1 = "alDous Huxley was born in 1894.".split(" ")
def normallize(name):
    return name.capitalize()
result = list(map(normallize,str1))
print(result)

4.对字符串"Where now? Who now? When now?"调用一个方法,返回如下述
的列表[“Where now?”, “Who now?”, “When now?”]。

str1 = "Where now? Who now? When now?".split("?")
str2 = "?".join(str1)
print(str2)

5.对列表[“The”, “fox”, “jumped”, “over”, “the”, “fence”, “.”]
进行处理,将其变成一个语法正确的字符串。每个单词间以空格符分隔,但是单词
fence 和句号之间不能有空格符。(别忘了,我们之前已经学过将字符串列表连接为单
个字符串的方法。)

str1 = ["The", "fox", "jumped", "over", "the", "fence"]
result = " ".join(str1) + "."

print(result)

6.将字符串"A screaming comes across the sky."中所有的"s"字符替换
为美元符号。

result = "A screaming comes across the sky.". replace("s" , "$")
print(result)

7.找到字符串"Hemingway"中字符"m"所在的第一个索引。

result = "Hemingway" . index("m")
print(result)


8.在你最喜欢的书中找一段对话,将其变成一个字符串。

9.先后使用字符串拼接和字符串乘法,创建字符串"three three three"。

print("three" + " " + "three" + " " + "three" )

10.对字符串"It was bright cold day in April, and the clocks were
striking thirteen."进行切片,只保留逗号之前的字符。

str1 = """It was bright cold day in April,
        and the clocks were striking thirteen."""
num = str1 . index(",")
result = str1[0:num]
print(result)

发布了42 篇原创文章 · 获赞 0 · 访问量 270

猜你喜欢

转载自blog.csdn.net/qq_43169516/article/details/103909867
今日推荐