Python の文字列ライブラリには多数の関数があります。文字列関数は文字列自体を変更せず、変更された文字列を返します。これらの機能により、時間を大幅に節約できます。
構文: string_name.function_name()
line='Hello World' temp= line.lower() print(temp) >> hello world
text = 'Hello World' temp = text.upper() print(temp) Output: HELLO WORLD
s="python is fun" c=s.capitalize() print(c) >>Python is fun
s="hello world" c=s.title() print(c) >>Hello World
text = ' Hello World ' temp = text.strip() print(text) print(temp) Output: Hello World Hello World
text = ' Hello World ' temp = text.lstrip() print(text) print(temp) Output: Hello World Hello World
text = ' Hello World ' temp = text.lstrip() print(text) print(temp) Output: Hello World Hello World
text = 'Banana' temp = text.count('a') print(text) print(temp) Output: Banana 3
text = 'Hello' temp = text.startswith('He') print(text) print(temp) Output: Hello True
text = 'Hello' temp =text.endswith('hi') print(text) print(temp) Output: Hello False
Ex: text = 'Banana' temp = text.find('a') print(text) print(temp) Output: Banana 1
text = 'Hello' temp = text.replace('l','nt') print(text) print(temp) Output: Hello Hentnto
dir('This is a string') / dir(' '):Python に存在するすべての文字列関数を確認します。
2 つの方法を併用できます。
名前=name.strip().title()
=>;機械はテキストはおろか、小数点さえも理解できません。マシンはバイナリのみを理解します。
「a」(文字列)と書いても理解できません。理解するために、機械はそれらをバイナリに変換します。その場合、文字列をバイナリに変換するには、まず文字列を数値に変換する必要があります。そこで ASCII が登場します。
ASCII (American Standard Code for Information Interchange) は、英語の文字を 0 から 127 までの番号で表すためのコードです。
Ord: ord 関数は、文字の対応する ASCII 値を返します。
Ord('a') >> 97 Ord('b') >> 98
Chr: chr 関数は、対応する数値の文字列を返します。
Chr(97) >>a
ASCII コード表
例の問題
次に、問題の問題を伴う機能とASCIIコードの知識を使用しようとします。
問題:この問題では、ユーザーに大文字で何かを書くように依頼すると、コードは同じテキストを小文字で返します。ここでは、ユーザーがテキストを提供し、他に何も提供しないことを期待しています。
ソリューション1:default .lower()function を使用しています
line='Hello World' temp= line.lower() print(temp) >> hello world
ソリューション2:default .lower()function を使用せずに
さあ、この問題を別の方法で解決してみましょう。今回は、デフォルトの.lower()関数を使用しません。デフォルトの関数なしにこの問題を解決する必要がある理由を尋ねることができますが、デフォルトの関数は私たちの生活を楽にするためにあります。それは本当ですが、これらのデフォルトの機能がどのように機能するかを理解することは素晴らしい習慣でもあります。これらの機能のコアメカニクスを理解すると、プログラミングスキルが開発されます。それで、ASCII値を使用してテキストを小文字に変換しようとします。
このソリューションは、大文字の文字列に小さな文字があっても機能します。
text = 'Hello World' temp = text.upper() print(temp) Output: HELLO WORLD
コードで32のアディトンを行った理由について考えてみてください。 ASCIIコード画像を見て、
について考えるだから、これは今日のためです。必要なときにいつでも文字列のデフォルト機能を使用できるようになりました。また、ASCIIコードを使用して関数がわからない場合でも、問題を解決する方法も考えています。ハッピーコーディング!
以上がPython の基本 文字列部分 文字列関数と ASCII コードの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。