2022年4月22日:面向初学者的Python--在Python中使用字符串(运行失败)

Python中的字符串基础知识

字符串的不可变性

关于使用引号

多行文本

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> multiline="Facts about the Moon:\n There is no atmosphere.\n There is no sound."
>>> print(multiline)
Facts about the Moon:
 There is no atmosphere.
 There is no sound.
>>> multiline="""Facts about the Moon:
...  There is no atmosphere.
...  There is no sound."""
>>> print(multiline)
Facts about the Moon:
 There is no atmosphere.
 There is no sound.
>>>


Python中的字符串方法

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> "temperatures and facets about the moon".title()
'Temperatures And Facets About The Moon'
>>> heading="temperatures and facts about the moon"
>>> heading.title()
'Temperatures And Facts About The Moon'
>>>

拆分字符串

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> temperatures="""Daylight: 260 F
... Nighttime: -200 F"""
>>> temperatures.split()
['Daylight:', '260', 'F', 'Nighttime:', '-200', 'F']
>>> temperatures.split('\n')
['Daylight: 260 F', 'Nighttime: -200 F']
>>>

搜索字符串

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> "Moon" in "This text will describe facts and challenges with space travel"
False
>>> "Moon" in "This text will describe facts about the Moon"
True
>>> temperatures="""Saturn has a daytime temperature of -170 degrees Celsius,
... while Mars has -28 Celsius."""
>>> temperatures.find("Moon")
-1
>>> temperatures.find("Mars")
64
>>> temperatures.count("Mars")
1
>>> temperatures.count("Moon")
0
>>> "The Moon And The Earth".lower()
'the moon and the earth'
>>> "The Moon And The Earth".upper()
'THE MOON AND THE EARTH'
>>>

 要检查特定单词在字符串中的位置,一种方法是使用.find()方法。

如果找不到该单词,.find()方法会返回-1;否则它将返回索引(表示字符串中的位置的数字)。

搜索内容的另一种操作是使用.count()方法,这将返回某个单词在字符串出现 的总次数。

Python中的字符串区分大小写。

检查内容

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> temperatures="Mars Average Temperature: -60 C"
>>> parts=temperatures.split(':')
>>> parts
['Mars Average Temperature', ' -60 C']
>>> parts[-1]
' -60 C'
>>> mars_temperature="The highest temperature on Mars is about 30 C"
>>> for item in mars_temperature.split():
...     if item.isnumeric():
...             print(item)
...
30
>>> "-60".startswith('-')
True
>>> if "30 C".endswith("C");
  File "<stdin>", line 1
    if "30 C".endswith("C");
                           ^
SyntaxError: invalid syntax
>>> if "30 C".endswith("C"):
  File "<stdin>", line 1
    if "30 C".endswith("C"):
                           ^
SyntaxError: invalid character ':' (U+FF1A)
>>> if "30 C".endswith("C"):
... print("This temperature is in Celsius")
  File "<stdin>", line 2
    print("This temperature is in Celsius")
    ^
IndentationError: expected an indented block after 'if' statement on line 1
>>> if "30 C".endswith("C"):
...     print("This temperature is in Celsius")
...
This temperature is in Celsius
>>>

转换文本

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> "Saturn has a daytime temperature of -170 degrees Celsius, while Mars has -28 Celsius.".replace("Celsius","C")
'Saturn has a daytime temperature of -170 degrees C, while Mars has -28 C.'
>>> text="Temperatures on the Moon can vary wildly."
>>> "temperatures" in text
False
>>> "temperatures" in text.lower()
True
>>> moon_facts=["The Moon is drifting away from the Earth.","On average, the Moon is moving about 4cm every year"]
>>> '\n'.join(moon_facts)
'The Moon is drifting away from the Earth.\nOn average, the Moon is moving about 4cm every year'
>>>

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> text="""Interesting facts about the Moon. The Moon is Earth's only satellite. There are several interesting facts about the Moon and how it affects life here on Earth.
... On average, the Moon moves 4cm away from the Earth every year. This yearly drift is not significant enough to cause immediate effects on Earth. The highest daylight temperature of the Moon is 127 C."""
>>> sentences=text.split('. ')
>>> print(sentences)
['Interesting facts about the Moon', "The Moon is Earth's only satellite", 'There are several interesting facts about the Moon and how it affects life here on Earth', '\nOn average, the Moon moves 4cm away from the Earth every year', 'This yearly drift is not significant enough to cause immediate effects on Earth', 'The highest daylight temperature of the Moon is 127 C.']
>>> for sentence in sentences:
...     if 'temperature' in sentence:
...             print(sentence)
...
The highest daylight temperature of the Moon is 127 C.
>>>

Python中的字符串格式

百分号(%)格式

占位符是%s,变量被 传递到字符串外%字符后面的文本上。

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> mass_percentage="1/6"
>>> print("On the Moon, you would weigh about %s of your weight on Earth" % mass_percentage)
On the Moon, you would weigh about 1/6 of your weight on Earth
>>> print("""Both sides of the %s get the same amount of sunlight,
... but only one side is seen from %s because
... the %s rotates around its own axis when it orbits %s."""%("Moon',"Earth","Moon","Earth"))
  File "<stdin>", line 3
    the %s rotates around its own axis when it orbits %s."""%("Moon',"Earth","Moon","Earth"))
                                                              ^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
>>> print("""Both sides of the %s get the same amount of sunlight,
... but only one side is seen from %s because
... the %s rotates around its own axis when it orbits %s."""%("Moon","Earth","Moon","Earth"))
Both sides of the Moon get the same amount of sunlight,
but only one side is seen from Earth because
the Moon rotates around its own axis when it orbits Earth.
>>>

22点钟,天晚了,第二天继续写。

format()方法

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> mass_percentage="1/6"
>>> print("On the Moon, you would weigh about {} of your weight on Earth".format(mass_percentage))
On the Moon, you would weigh about 1/6 of your weight on Earth
>>> print("""You are lighter on the {0}, because on the {0}
... you would weigh about {1} of your weight on Earth""".format("Moon",mass_percentage))
You are lighter on the Moon, because on the Moon
you would weigh about 1/6 of your weight on Earth
>>> print("""You are lighter on the {moon}, because on the {moon}
... you would weight about {mass} of your weight on Earth""".format(moon="Moon",mass=mass_percentage))
You are lighter on the Moon, because on the Moon
you would weight about 1/6 of your weight on Earth
>>>

关于f-string

>>> print(f"On the Moon, you would weigh about {mass_percentage} of your weight on Earth")
On the Moon, you would weigh about 1/6 of your weight on Earth
>>> round(100/6,1)
16.7
>>> print(f"On the Moon, you would weigh about {round(100/6,1)}% of your weight on Earth")
On the Moon, you would weigh about 16.7% of your weight on Earth
>>> subject="interesting facts about the moon"
>>> f"{subject.title()}
  File "<stdin>", line 1
    f"{subject.title()}
    ^
SyntaxError: unterminated string literal (detected at line 1)
>>> f''{subject.title()}
  File "<stdin>", line 1
    f''{subject.title()}
       ^
SyntaxError: invalid syntax
>>>

 最后一个代码不对了。

2022年4月23日上午做完了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值