【Python組み込み型】「str」のサンプルコード

Python

こちらは「str」(Python組み込み型)のサンプルコードについての記事となっております。

基本情報 … Basic Information

Pythonの「str」とは、文字列を表すデータ型の一つです。「str」は文字列を表すため、Pythonで文字列を表現する際には必ず「str」を使います。文字列とは、文字の並びであり、例えば「hello, world!」や「1234」などが該当します。「str」はイミュータブル(不変)なデータ型であり、一度作成された文字列オブジェクトの内容を変更することはできません。また、「str」は、シングルクォーテーション(‘)、ダブルクォーテーション(“)、トリプルクォーテーション(”’)のどれかで文字列を定義することができます。文字列に対して、様々な操作を行うことができます。例えば、文字列の結合、分割、検索、置換、フォーマットなどがあります。

チートシート … Cheat Sheet

Create a Empty Stringa=””“”
Create a Empty Stringa=str()“”
Create a Stringa=”string”“string”
Edit a String with Conditiona = input_str.capitalize()A. “one two three.”
B. “four. five. six.”
A. “One two three.”
B. “Four. five. six.”
Edit a String with Conditiona = input_str.title()A. “one two three.”
B. “four. five. six.”
A. “One Two Three.”
B. “Four. Five. Six.”
Edit a String with Conditiona = input_str.casefold()A. “One”
B. “TWO”
A. “one”
B. “two”
Edit a String with Conditiona = input_str.lower()A. “One, Two. Three.”
B. “FOUR, FIVE. SIX.”
C. “Seven, eIght. niNe.”
A. “one, two. three.”
B. “four, five. six.”
C. “seven, eight. nine.”
Edit a String with Conditiona = input_str.upper()A. “One, Two. Three.”
B. “FOUR, FIVE. SIX.”
C. “Seven, eIght. niNe.”
A. “ONE, TWO. THREE.”
B. “FOUR, FIVE. SIX.”
C. “SEVEN, EIGHT. NINE.”
Edit a String with Conditiona = input_str.swapcase()A. “One, Two. Three.”
B. “FOUR, FIVE. SIX.”
C. “Seven, eIght. niNe.” D. “tEn, elEven. twElve.”
A. “oNE, tWO. tHREE.”
B. “FOUR, FIVE. SIX.”
C. “seven, eight. nine.”
D. “TeN, ELeVEN. TWeLVE.”
Edit a String with Conditiona = input_str.center(target_len)A. “odd”, 10
B. “even”, 10
C. “odd”, 11
D. “even”, 11
A. [ odd ]
B. [ even ]
C. [ odd ]
D. [ even ]
Edit a String with Conditiona = input_str.center(target_len,target_str)A. “odd”, 10, “*”
B. “even”, 10, “*”
C. “odd”, 11, “*”
D. “even”, 11, “*”
A. [***odd****]
B. [***even***]
C. [****odd****]
D. [****even***]
Edit a String with Conditiona = input_str.ljust(target_len)“apple”, 10[apple ]
Edit a String with Conditiona = input_str.ljust(target_len,target_str)“apple”, 10, “*”[apple*****]
Edit a String with Conditiona = input_str.rjust(target_len)“apple”, 10[ apple]
Edit a String with Conditiona = input_str.rjust(target_len,target_str)“apple”, 10, “*”[*****apple]
Edit a String with Conditiona = input_str.zfill(target_len)A. “123”, 5
B. “one”, 5
C. “123”, 1
A. 00123
B. 00one
C. 123
Edit a String with Conditiona = input_str.lstrip()A. ” apple banana ”
B. ” apple banana ”
C. “\tapple\tbanana\t”
D. “\t\tapple\t\tbanana\t\t”
E. “\napple\nbanana\n”
F. “\n\napple\n\nbanana\n\n”
A. ‘apple banana ‘
B. ‘apple banana ‘
C. ‘apple\tbanana\t’
D. ‘apple\t\tbanana\t\t’
E. ‘apple\nbanana\n’
F. ‘apple\n\nbanana\n\n’
Edit a String with Conditiona = input_str.rstrip()A. ” apple banana ”
B. ” apple banana ”
C. “\tapple\tbanana\t”
D. “\t\tapple\t\tbanana\t\t”
E. “\napple\nbanana\n”
F. “\n\napple\n\nbanana\n\n”
A. ‘ apple banana’
B. ‘ apple banana’
C. ‘\tapple\tbanana’
D. ‘\t\tapple\t\tbanana’
E. ‘\napple\nbanana’
F. ‘\n\napple\n\nbanana’
Edit a String with Conditiona = input_str.strip()A. ” apple banana ”
B. ” apple banana ”
C. “\tapple\tbanana\t”
D. “\t\tapple\t\tbanana\t\t”
E. “\napple\nbanana\n”
F. “\n\napple\n\nbanana\n\n”
A. ‘apple banana’
B. ‘apple banana’
C. ‘apple\tbanana’
D. ‘apple\t\tbanana’
E. ‘apple\nbanana’
F. ‘apple\n\nbanana’
Get an ID of the String with Valuea = input_str.find(target_str)A. “apple, banana, cherry”, “apple”
B. “apple, apple, apple”, “apple”
C. “apple, banana, cherry”, “a”
D. “apple, banana, cherry”, “z”
A. 0
B. 0
C. 0
D. -1
Get an ID of the String with Valuea = input_str.index(target_str)
* ValueError
A. “apple, banana, cherry”, “apple”
B. “apple, apple, apple”, “apple”
C. “apple, banana, cherry”, “a”
D. “apple, banana, cherry”, “z”
A. 0
B. 0
C. 0
D. ValueError
Get an ID of the String with Valuea = input_str.rfind(target_str)A. “apple, banana, cherry”, “apple”
B. “apple, apple, apple”, “apple”
C. “apple, banana, cherry”, “a”
D. “apple, banana, cherry”, “z”
A. 0
B. 14
C. 12
D. -1
Get an ID of the String with Valuea = input_str.rindex(target_str)
* ValueError
A. “apple, banana, cherry”, “apple”
B. “apple, apple, apple”, “apple”
C. “apple, banana, cherry”, “a”
D. “apple, banana, cherry”, “z”
A. 0
B. 14
C. 12
D. ValueError
Convert the String to Tuplea = input_str.partition(target_str)A. “apple, banana, cherry”, “apple”
B. “apple, apple, apple”, “apple”
C. “apple, banana, cherry”, “a”
D. “apple, banana, cherry”, “z”
A. (”, ‘apple’, ‘, banana, cherry’)
B. (”, ‘apple’, ‘, apple, apple’)
C. (”, ‘a’, ‘pple, banana, cherry’)
D. (‘apple, banana, cherry’, ”, ”)
Convert the String to Tuplea = input_str.rpartition(target_str)A. “apple, banana, cherry”, “apple”
B. “apple, apple, apple”, “apple”
C. “apple, banana, cherry”, “a”
D. “apple, banana, cherry”, “z”
A. (”, ‘apple’, ‘, banana, cherry’)
B. (‘apple, apple, ‘, ‘apple’, ”)
C. (‘apple, banan’, ‘a’, ‘, cherry’)
D. (”, ”, ‘apple, banana, cherry’)
Count the Word/Text in the Stringa = input_str.count(target_str)A. “apple, banana, cherry”, “apple”
B. “apple, apple, apple”, “apple”
C. “apple, banana, cherry”, “a”
D. “apple, banana, cherry”, “z”
A. 1
B. 3
C. 4
D. 0
Create the StringA. “{f1}, {f2}, {f3}”.format(f1=”apple”,f2=”banana”,f3=”cherry”)
B. “{0}, {1}, {2}”.format(“apple”,”banana”,”cherry”)
C. “{}, {}, {}”.format(“apple”,”banana”,”cherry”)
apple, banana, cherry
Check the Stringa = input_str.startswith(target_str)A. “AAA”, “A”
B. “AAA”, “AA”
C. “AAA”, “a”
A. True
B. True
C. False
Check the Stringa = input_str.endswith(target_str)A. “AAA”, “A”
B. “AAA”, “AA”
C. “AAA”, “a”
A. True
B. True
C. False
Check the Stringa = input_str.isalpha()A. “abc”
B. “123”
C. “あいう”
D. “sample\n”
E. “sample!?”
A. True
B. False
C. True
D. False
E. False
Check the Stringa = input_str.islower()A. “One”
B. “TWO”
C. “three”
D. “sample\n”
E. “sample!?”
A. False
B. False
C. True
D. True
E. True
Check the Stringa = input_str.isupper()A. “One”
B. “TWO”
C. “three”
D. “SAMPLE\n”
E. “SAMPLE!?”
A. False
B. True
C. False
D. True
E. True
Check the Stringa = input_str.isidentifier()A. “abc”
B. “123”
C. “あいう”
D. “sample\n”
E. “sample!?”
A. True
B. False
C. True
D. False
E. False
Check the Stringa = input_str.isdecimal()A. “abc”
B. “123”
C. “あいう”
D. “一二三”
E. “123”
F. “-123”
G. “ー123”
H. “-1.23”
A. False
B. True
C. False
D. False
E. True
F. False
G. False
H. False
Check the Stringa = input_str.isdigit()A. “abc”
B. “123”
C. “あいう”
D. “一二三”
E. “123”
F. “-123”
G. “ー123”
H. “-1.23”
A. False
B. True
C. False
D. False
E. True
F. False
G. False
H. False
Check the Stringa = input_str.isnumeric()A. “abc”
B. “123”
C. “あいう”
D. “一二三”
E. “123”
F. “-123”
G. “ー123”
H. “-1.23”
A. False
B. True
C. False
D. True
E. True
F. False
G. False
H. False
Check the Stringa = input_str.isalnum()A. “abc”
B. “123”
C. “あいう”
D. “sample\n”
E. “sample!?”
A. True
B. True
C. True
D. False
E. False
Check the Stringa = input_str.istitle()A. “One, Two. Three.”
B. “ONE, TWO. THREE.”
C. “1, 2. 3.”
D. “One, TWO. 3.”
A. True
B. False
C. False
D. False
Check the Stringa = input_str.isprintable()A. “sample”
B. “sample\n”
C. “sample!?”
A. True
B. False
C. True
Check the Stringa = input_str.isspace()A. “”
B. ” ”
C. ” ”
D. “\t”
E. “\n”
A. False
B. True
C. True
D. True
E. True
Encoding with “utf-8”a = input_str.encode(encoding=”utf-8″)“あいうえお”b’\xe3\x81\x82\xe3\x81
\x84\xe3\x81\x86\xe3\
x81\x88\xe3\x81\x8a’
Encoding with “shift_jis”a = input_str.encode(encoding=”shift_jis”)“あいうえお”b’\x82\xa0\x82\xa2\x82
\xa4\x82\xa6\x82\xa8′
Decoding with “utf-8”a = input_str.decode(encoding=”utf-8″)b’\xe3\x81\x82\xe3\x81
\x84\xe3\x81\x86\xe3\
x81\x88\xe3\x81\x8a’
“あいうえお”
Decoding with “shift_jis”a = input_str.decode(encoding=”shift_jis”)b’\x82\xa0\x82\xa2\x82
\xa4\x82\xa6\x82\xa8′
“あいうえお”
Edit the String with Conditiona = input_str.expandtabs(target_num)A. “a\tp\tp\tl\te”, 2
B. “a\tp\tp\tl\te”, 0
A. “a p p l e”
B. “apple”
Convert the String to Lista = input_str.split(split_str)“one, two, three, four, five”, “, “[‘one’, ‘two’, ‘three’, ‘four’, ‘five’]
Convert the String to Lista = input_str.split(split_str, target_num)A. “one, two, three, four, five”, “, “, 0
B. “one, two, three, four, five”, “, “, 1
A. [‘one, two, three, four, five’]
B. [‘one’, ‘two, three, four, five’]
Convert the String to Lista = input_str.rsplit(split_str)“one, two, three, four, five”, “, “[‘one’, ‘two’, ‘three’, ‘four’, ‘five’]
Convert the String to Lista = input_str.rsplit(split_str, target_num)A. “one, two, three, four, five”, “, “, 0
B. “one, two, three, four, five”, “, “, 1
A. [‘one, two, three, four, five’]
B. [‘one, two, three, four’, ‘five’]
Convert the String to Lista = input_str.splitlines()A. “one, two.\nthree.”
B. “\none, two.three.”
C. “one, two.three.\n”
A. [‘one, two.’, ‘three.’]
B. [”, ‘one, two.three.’]
C. [‘one, two.three.’]
Convert the List to String“_”.join(input_list)[“one”,”two”,”three”]one_two_three
Convert the Tuple to String“_”.join(input_tuple)(“one”,”two”,”three”)one_two_three
Convert the Set to String“_”.join(input_set){“one”,”two”,”three”}three_two_one
Convert the Dictionary to String“_”.join(input_dict){“one”:”ichi”,”two”:”ni”,”three”:”san”}one_two_three
Edit the String with Conditiona = input_str.translate(input_str.maketrans(from_str,to_str))A. “ababacddeee”, “b”, “z”
B. “ababacddeee”, “abc”, “xyz”
A. “azazacddeee”
B. “xyxyxzddeee”
Edit the String with Conditiona = input_str.translate(input_str.maketrans(from_str,to_str,del_str))
* delete > translate
A. “ababacddeee”, “abc”, “xyz”, “de”
B. “ababacddeee”, “abc”, “xyz”, “ce”
C. “ababacddeee”, “abc”, “xyz”, “wx”
A. “xyxyxz”
B. “xyxyxdd”
C. “xyxyxzddeee”
Edit the String with Conditiona = input_str.replace(from_str, to_str)A. “apple, banana, cherry”, “apple”, “ringo”
B. “apple, apple, apple”, “apple”, “ringo”
C. “ababacddbeee”, “b”, “z”
D. “ababacddbeee”, “b”, “zzz”
E. “ababacddbeee”, “ba”, “z”
A. “ringo, banana, cherry”
B. “ringo, ringo, ringo”
C. “azazacddzeee”
D. “azzzazzzacddzzzeee”
E. “azzcddbeee”

サンプルコード … Sample Code

###############################################################################

### Create String
EMPTY_STR = ""      ### str()
STR_1 = "One"
STR_2 = "TWO"
STR_3 = "three"

### First Character to Upper Case
sentence_STR_1 = "one two three."
sentence_STR_2 = "four. five. six."

cap_STR_1 = sentence_STR_1.capitalize()
cap_STR_2 = sentence_STR_2.capitalize()

### print(cap_STR_1)    ### One two three.
### print(cap_STR_2)    ### Four. five. six.

### All Characters to Upper Case
sentence_STR_1 = "one two three."
sentence_STR_2 = "four. five. six."

title_STR_1 = sentence_STR_1.title()
title_STR_2 = sentence_STR_2.title()

### print(title_STR_1)    ### One Two Three.
### print(title_STR_2)    ### Four. Five. Six.

### All Characters to Lower Case
STR_1 = "One"
STR_2 = "TWO"

low_STR_1 = STR_1.casefold()
low_STR_2 = STR_2.casefold()

### print(low_STR_1)    ### one
### print(low_STR_2)    ### two

### All Characters to Lower Case

sentence_STR_1 = "One, Two. Three."
sentence_STR_2 = "FOUR, FIVE. SIX."
sentence_STR_3 = "Seven, eIght. niNe."

new_STR_1 = sentence_STR_1.lower()
new_STR_2 = sentence_STR_2.lower()
new_STR_3 = sentence_STR_3.lower()

### print(new_STR_1)        ### one, two. three.
### print(new_STR_2)        ### four, five. six.
### print(new_STR_3)        ### seven, eight. nine.

### All Characters to Upper Case

sentence_STR_1 = "One, Two. Three."
sentence_STR_2 = "four, five. six."
sentence_STR_3 = "Seven, eIght. niNe."

new_STR_1 = sentence_STR_1.upper()
new_STR_2 = sentence_STR_2.upper()
new_STR_3 = sentence_STR_3.upper()

### print(new_STR_1)        ### ONE, TWO. THREE.
### print(new_STR_2)        ### FOUR, FIVE. SIX.
### print(new_STR_3)        ### SEVEN, EIGHT. NINE.

### All Characters to Swap Case

sentence_STR_1 = "One, Two. Three."
sentence_STR_2 = "four, five. six."
sentence_STR_3 = "SEVEN, EIGHT. NINE."
sentence_STR_4 = "tEn, elEven. twElve."

new_STR_1 = sentence_STR_1.swapcase()
new_STR_2 = sentence_STR_2.swapcase()
new_STR_3 = sentence_STR_3.swapcase()
new_STR_4 = sentence_STR_4.swapcase()

### print(new_STR_1)        ### oNE, tWO. tHREE.
### print(new_STR_2)        ### FOUR, FIVE. SIX.
### print(new_STR_3)        ### seven, eight. nine.
### print(new_STR_4)        ### TeN, ELeVEN. TWeLVE.

### Create String
STR_1 = "odd"
STR_2 = "even"

new_STR_1 = STR_1.center(10)
new_STR_2 = STR_2.center(10)
new_STR_3 = STR_1.center(11)
new_STR_4 = STR_2.center(11)

### print(f"[{new_STR_1}]")     ### [   odd    ]
### print(f"[{new_STR_2}]")     ### [   even   ]
### print(f"[{new_STR_3}]")     ### [    odd    ]
### print(f"[{new_STR_4}]")     ### [    even   ]

STR_1 = "odd"
STR_2 = "even"

new_STR_1 = STR_1.center(10,"*")
new_STR_2 = STR_2.center(10,"*")
new_STR_3 = STR_1.center(11,"*")
new_STR_4 = STR_2.center(11,"*")

### print(f"[{new_STR_1}]")     ### [***odd****]
### print(f"[{new_STR_2}]")     ### [***even***]
### print(f"[{new_STR_3}]")     ### [****odd****]
### print(f"[{new_STR_4}]")     ### [****even***]

### Create String
STR_1 = "apple"

new_STR_1 = STR_1.ljust(10)
new_STR_2 = STR_1.ljust(10,"*")

### print(f"[{new_STR_1}]")     ### [apple     ]
### print(f"[{new_STR_2}]")     ### [apple*****]

### Create String
STR_1 = "apple"

new_STR_1 = STR_1.rjust(10)
new_STR_2 = STR_1.rjust(10,"*")

### print(f"[{new_STR_1}]")     ### [     apple]
### print(f"[{new_STR_2}]")     ### [*****apple]

### Create String
STR_1 = "123"
STR_2 = "one"

new_STR_1 = STR_1.zfill(5)
new_STR_2 = STR_2.zfill(5)
new_STR_3 = STR_1.zfill(1)

### print(new_STR_1)            ### 00123
### print(new_STR_2)            ### 00one
### print(new_STR_3)            ### 123

### Create String

STR_1 = " apple banana "
STR_2 = "  apple  banana  "
STR_3 = "\tapple\tbanana\t"
STR_4 = "\t\tapple\t\tbanana\t\t"
STR_5 = "\napple\nbanana\n"
STR_6 = "\n\napple\n\nbanana\n\n"

new_STR_1 = STR_1.lstrip()
new_STR_2 = STR_2.lstrip()
new_STR_3 = STR_3.lstrip()
new_STR_4 = STR_4.lstrip()
new_STR_5 = STR_5.lstrip()
new_STR_6 = STR_6.lstrip()

### print(repr(STR_1))          ### ' apple banana '
### print(repr(new_STR_1))      ### 'apple banana '
### print(repr(STR_2))          ### '  apple  banana  '
### print(repr(new_STR_2))      ### 'apple  banana  '
### print(repr(STR_3))          ### '\tapple\tbanana\t'
### print(repr(new_STR_3))      ### 'apple\tbanana\t'
### print(repr(STR_4))          ### '\t\tapple\t\tbanana\t\t'
### print(repr(new_STR_4))      ### 'apple\t\tbanana\t\t'
### print(repr(STR_5))          ### '\napple\nbanana\n'
### print(repr(new_STR_5))      ### 'apple\nbanana\n'
### print(repr(STR_6))          ### '\n\napple\n\nbanana\n\n'
### print(repr(new_STR_6))      ### 'apple\n\nbanana\n\n'

### Create String

STR_1 = " apple banana "
STR_2 = "  apple  banana  "
STR_3 = "\tapple\tbanana\t"
STR_4 = "\t\tapple\t\tbanana\t\t"
STR_5 = "\napple\nbanana\n"
STR_6 = "\n\napple\n\nbanana\n\n"

new_STR_1 = STR_1.rstrip()
new_STR_2 = STR_2.rstrip()
new_STR_3 = STR_3.rstrip()
new_STR_4 = STR_4.rstrip()
new_STR_5 = STR_5.rstrip()
new_STR_6 = STR_6.rstrip()

### print(repr(STR_1))          ### ' apple banana '
### print(repr(new_STR_1))      ### ' apple banana'
### print(repr(STR_2))          ### '  apple  banana  '
### print(repr(new_STR_2))      ### '  apple  banana'
### print(repr(STR_3))          ### '\tapple\tbanana\t'
### print(repr(new_STR_3))      ### '\tapple\tbanana'
### print(repr(STR_4))          ### '\t\tapple\t\tbanana\t\t'
### print(repr(new_STR_4))      ### '\t\tapple\t\tbanana'
### print(repr(STR_5))          ### '\napple\nbanana\n'
### print(repr(new_STR_5))      ### '\napple\nbanana'
### print(repr(STR_6))          ### '\n\napple\n\nbanana\n\n'
### print(repr(new_STR_6))      ### '\n\napple\n\nbanana'

### Create String

STR_1 = " apple banana "
STR_2 = "  apple  banana  "
STR_3 = "\tapple\tbanana\t"
STR_4 = "\t\tapple\t\tbanana\t\t"
STR_5 = "\napple\nbanana\n"
STR_6 = "\n\napple\n\nbanana\n\n"

new_STR_1 = STR_1.strip()
new_STR_2 = STR_2.strip()
new_STR_3 = STR_3.strip()
new_STR_4 = STR_4.strip()
new_STR_5 = STR_5.strip()
new_STR_6 = STR_6.strip()

### print(repr(STR_1))          ### ' apple banana '
### print(repr(new_STR_1))      ### 'apple banana'
### print(repr(STR_2))          ### '  apple  banana  '
### print(repr(new_STR_2))      ### 'apple  banana'
### print(repr(STR_3))          ### '\tapple\tbanana\t'
### print(repr(new_STR_3))      ### 'apple\tbanana'
### print(repr(STR_4))          ### '\t\tapple\t\tbanana\t\t'
### print(repr(new_STR_4))      ### 'apple\t\tbanana'
### print(repr(STR_5))          ### '\napple\nbanana\n'
### print(repr(new_STR_5))      ### 'apple\nbanana'
### print(repr(STR_6))          ### '\n\napple\n\nbanana\n\n'
### print(repr(new_STR_6))      ### 'apple\n\nbanana'

### Find Character/String

STR_1 = "apple, banana, cherry"
STR_2 = "apple, apple, apple"

find_INT_1 = STR_1.find("apple")
find_INT_2 = STR_2.find("apple")

find_INT_3 = STR_1.find("a")
find_INT_4 = STR_1.find("z")

### print(find_INT_1)       ### 0
### print(find_INT_2)       ### 0
### print(find_INT_3)       ### 0
### print(find_INT_4)       ### -1

### Find Character/String

STR_1 = "apple, banana, cherry"
STR_2 = "apple, apple, apple"

index_INT_1 = STR_1.index("apple")
index_INT_2 = STR_2.index("apple")
index_INT_3 = STR_1.index("a")

### index_INT_4 = STR_1.index("z")  
### ValueError: substring not found

### print(index_INT_1)       ### 0
### print(index_INT_2)       ### 0
### print(index_INT_3)       ### 0

### Find Character/String

STR_1 = "apple, banana, cherry"
STR_2 = "apple, apple, apple"

index_INT_1 = STR_1.rfind("apple")
index_INT_2 = STR_2.rfind("apple")
index_INT_3 = STR_1.rfind("a")
index_INT_4 = STR_1.rfind("z")  

### print(index_INT_1)       ### 0
### print(index_INT_2)       ### 14
### print(index_INT_3)       ### 12
### print(index_INT_4)       ### -1

### Find Character/String

STR_1 = "apple, banana, cherry"
STR_2 = "apple, apple, apple"

rindex_INT_1 = STR_1.rindex("apple")
rindex_INT_2 = STR_2.rindex("apple")
rindex_INT_3 = STR_1.rindex("a")
### index_INT_4 = STR_1.rindex("z")  
### ValueError: substring not found

### print(rindex_INT_1)       ### 0
### print(rindex_INT_2)       ### 14
### print(rindex_INT_3)       ### 12

### Find Character/String

STR_1 = "apple, banana, cherry"
STR_2 = "apple, apple, apple"

part_INT_1 = STR_1.partition("apple")
part_INT_2 = STR_2.partition("apple")
part_INT_3 = STR_1.partition("a")
part_INT_4 = STR_1.partition("z")  

### print(part_INT_1)       ### ('', 'apple', ', banana, cherry')
### print(part_INT_2)       ### ('', 'apple', ', apple, apple')
### print(part_INT_3)       ### ('', 'a', 'pple, banana, cherry')
### print(part_INT_4)       ### ('apple, banana, cherry', '', '')

### Find Character/String

STR_1 = "apple, banana, cherry"
STR_2 = "apple, apple, apple"

rpart_INT_1 = STR_1.rpartition("apple")
rpart_INT_2 = STR_2.rpartition("apple")
rpart_INT_3 = STR_1.rpartition("a")
rpart_INT_4 = STR_1.rpartition("z")  

### print(rpart_INT_1)       ### ('', 'apple', ', banana, cherry')
### print(rpart_INT_2)       ### ('apple, apple, ', 'apple', '')
### print(rpart_INT_3)       ### ('apple, banan', 'a', ', cherry')
### print(rpart_INT_4)       ### ('', '', 'apple, banana, cherry')

### Count Character/String

STR_1 = "apple, banana, cherry"
STR_2 = "apple, apple, apple"

count_INT_1 = STR_1.count("apple")
count_INT_2 = STR_2.count("apple")

count_INT_3 = STR_1.count("a")
count_INT_4 = STR_1.count("z")

### print(count_INT_1)          ### 1
### print(count_INT_2)          ### 3
### print(count_INT_3)          ### 4
### print(count_INT_4)          ### 0

### Format

### apple, banana, cherry
### print("{fruit1}, {fruit2}, {fruit3}".format(fruit1="apple",fruit2="banana",fruit3="cherry"))
### print("{0}, {1}, {2}".format("apple","banana","cherry"))
### print("{}, {}, {}".format("apple","banana","cherry"))

### Check Start Character/String

STR_1 = "AAA"

### print(STR_1.startswith("A"))  ### True
### print(STR_1.startswith("AA")) ### True
### print(STR_1.startswith("a"))  ### False

### Check End Character/String

STR_1 = "AAA"

### print(STR_1.endswith("A"))  ### True
### print(STR_1.endswith("AA")) ### True
### print(STR_1.endswith("a"))  ### False

### Check Alphabet Character/String

STR_1 = "abc"
STR_2 = "123"
STR_3 = "あいう"
STR_4 = "sample\n"
STR_5 = "sample!?"

### print(STR_1.isalpha())      ### True
### print(STR_2.isalpha())      ### False
### print(STR_3.isalpha())      ### True
### print(STR_4.isalpha())      ### False
### print(STR_5.isalpha())      ### False

### Check Alphabet (Lower) Character/String

STR_1 = "One"
STR_2 = "TWO"
STR_3 = "three"
STR_4 = "sample\n"
STR_5 = "sample!?"

### print(STR_1.islower())      ### False
### print(STR_2.islower())      ### False
### print(STR_3.islower())      ### True
### print(STR_4.islower())      ### True
### print(STR_5.islower())      ### True

### Check Alphabet (Upper) Character/String

STR_1 = "One"
STR_2 = "TWO"
STR_3 = "three"
STR_4 = "SAMPLE\n"
STR_5 = "SAMPLE!?"

### print(STR_1.isupper())      ### False
### print(STR_2.isupper())      ### True
### print(STR_3.isupper())      ### False
### print(STR_4.isupper())      ### True
### print(STR_5.isupper())      ### True

### Check Valid Identifier Character/String

STR_1 = "abc"
STR_2 = "123"
STR_3 = "あいう"
STR_4 = "sample\n"
STR_5 = "sample!?"

### print(STR_1.isidentifier()) ### True
### print(STR_2.isidentifier()) ### False
### print(STR_3.isidentifier()) ### True
### print(STR_4.isidentifier()) ### False
### print(STR_5.isidentifier()) ### False

### Check Number Character/String

STR_1 = "abc"
STR_2 = "123"
STR_3 = "あいう"
STR_4 = "一二三"
STR_5 = "123"
STR_6 = "-123"
STR_7 = "ー123"
STR_8 = "-1.23"

### print(STR_1.isdecimal())      ### False
### print(STR_2.isdecimal())      ### True
### print(STR_3.isdecimal())      ### False
### print(STR_4.isdecimal())      ### False
### print(STR_5.isdecimal())      ### True
### print(STR_6.isdecimal())      ### False
### print(STR_7.isdecimal())      ### False
### print(STR_8.isdecimal())      ### False

### Check Number Character/String

STR_1 = "abc"
STR_2 = "123"
STR_3 = "あいう"
STR_4 = "一二三"
STR_5 = "123"
STR_6 = "-123"
STR_7 = "ー123"
STR_8 = "-1.23"

### print(STR_1.isdigit())      ### False
### print(STR_2.isdigit())      ### True
### print(STR_3.isdigit())      ### False
### print(STR_4.isdigit())      ### False
### print(STR_5.isdigit())      ### True
### print(STR_6.isdigit())      ### False
### print(STR_7.isdigit())      ### False
### print(STR_8.isdigit())      ### False

### Check Number Character/String

STR_1 = "abc"
STR_2 = "123"
STR_3 = "あいう"
STR_4 = "一二三"
STR_5 = "123"
STR_6 = "-123"
STR_7 = "ー123"
STR_8 = "-1.23"

### print(STR_1.isnumeric())      ### False
### print(STR_2.isnumeric())      ### True
### print(STR_3.isnumeric())      ### False
### print(STR_4.isnumeric())      ### True
### print(STR_5.isnumeric())      ### True
### print(STR_6.isnumeric())      ### False
### print(STR_7.isnumeric())      ### False
### print(STR_8.isnumeric())      ### False

### Check Alphabet&Number Character/String

STR_1 = "abc"
STR_2 = "123"
STR_3 = "あいう"
STR_4 = "sample\n"
STR_5 = "sample!?"

### print(STR_1.isalnum())      ### True
### print(STR_2.isalnum())      ### True
### print(STR_3.isalnum())      ### True
### print(STR_4.isalnum())      ### False
### print(STR_5.isalnum())      ### False

### Check Title

STR_1 = "One, Two. Three."
STR_2 = "ONE, TWO. THREE."
STR_3 = "1, 2. 3."
STR_4 = "One, TWO. 3."

### print(STR_1.istitle())  ### True
### print(STR_2.istitle())  ### False
### print(STR_3.istitle())  ### False
### print(STR_4.istitle())  ### False

### Check Printable

STR_1 = "sample"
STR_2 = "sample\n"
STR_3 = "sample!?"

### print(STR_1.isprintable())  ### True
### print(STR_2.isprintable())  ### False
### print(STR_3.isprintable())  ### True

### Check Space

STR_1 = ""
STR_2 = " "
STR_3 = "   "
STR_4 = "\t"
STR_5 = "\n"

### print(STR_1.isspace())  ### False
### print(STR_2.isspace())  ### True
### print(STR_3.isspace())  ### True
### print(STR_4.isspace())  ### True
### print(STR_5.isspace())  ### True

### Encode/Decode Character/String

STR_1 = "あいうえお"

enc_STR_1 = STR_1.encode(encoding="utf-8")
dec_STR_1 = enc_STR_1.decode(encoding="utf-8")

enc_STR_2 = STR_1.encode(encoding="shift_jis")
dec_STR_2 = enc_STR_2.decode(encoding="shift_jis")

### print(STR_1)        ### あいうえお
### print(enc_STR_1)    ### b'\xe3\x81\x82\xe3\x81\x84\xe3\x81\x86\xe3\x81\x88\xe3\x81\x8a'
### print(dec_STR_1)    ### あいうえお
### print(enc_STR_2)    ### b'\x82\xa0\x82\xa2\x82\xa4\x82\xa6\x82\xa8'
### print(dec_STR_2)    ### あいうえお

### Expand Tab

STR_1 = "a\tp\tp\tl\te"

### print(STR_1)                ### a       p       p       l       e
### print(STR_1.expandtabs(2))  ### a p p l e
### print(STR_1.expandtabs(0))  ### apple

### Convert String to List

STR_1 = "one, two, three, four, five"

split_LIST_1 = STR_1.split(", ")
split_LIST_2 = STR_1.split(", ",0)
split_LIST_3 = STR_1.split(", ",1)

### print(split_LIST_1)        ### ['one', 'two', 'three', 'four', 'five']
### print(split_LIST_2)        ### ['one, two, three, four, five']
### print(split_LIST_3)        ### ['one', 'two, three, four, five']

### Convert String to List

STR_1 = "one, two, three, four, five"

rsplit_LIST_1 = STR_1.rsplit(", ")
rsplit_LIST_2 = STR_1.rsplit(", ",0)
rsplit_LIST_3 = STR_1.rsplit(", ",1)

### print(rsplit_LIST_1)        ### ['one', 'two', 'three', 'four', 'five']
### print(rsplit_LIST_2)        ### ['one, two, three, four, five']
### print(rsplit_LIST_3)        ### ['one, two, three, four', 'five']

### Convert String to List

STR_1 = "one, two.\nthree."
STR_2 = "\none, two.three."
STR_3 = "one, two.three.\n"

splitlines_LIST_1 = STR_1.splitlines()
splitlines_LIST_2 = STR_1.splitlines()
splitlines_LIST_3 = STR_1.splitlines()

### print(splitlines_LIST_1)    ### ['one, two.', 'three.']
### print(splitlines_LIST_2)    ### ['one, two.', 'three.']
### print(splitlines_LIST_3)    ### ['one, two.', 'three.']

### Convert Iterable to String

SAMPLE_LIST  = ["one","two","three"]
SAMPLE_TUPLE = ("one","two","three")
SAMPLE_SET   = {"one","two","three"}
SAMPLE_DICT  = {"one":"ichi","two":"ni","three":"san"}

### print("_".join(SAMPLE_LIST))        ### one_two_three
### print("_".join(SAMPLE_TUPLE))       ### one_two_three
### print("_".join(SAMPLE_SET))         ### three_two_one
### print("_".join(SAMPLE_DICT))        ### one_two_three

### Replace Character

STR_1 = "ababacddeee"
trans_1 = STR_1.translate(STR_1.maketrans("b","z"))             ### a -> z
trans_2 = STR_1.translate(STR_1.maketrans("abc","xyz"))         ### a -> x, b -> y, c -> z
trans_3 = STR_1.translate(STR_1.maketrans("abc","xyz","ce"))    ### a -> x, b -> y, c -> z, ce -> remove
### print(trans_1)                      ### azazacddeee
### print(trans_2)                      ### xyxyxzddeee
### print(trans_3)                      ### xyxyxdd

### Replace String
STR_1 = "apple, banana, cherry"
STR_2 = "apple, apple, apple"
STR_3 = "ababacddeee"

replace_1 = STR_1.replace("apple", "ringo")
replace_2 = STR_2.replace("apple", "ringo")
replace_3 = STR_3.replace("b", "z")
replace_4 = STR_3.replace("b", "zzz")
replace_5 = STR_3.replace("ba", "z")

### print(replace_1)                    ### ringo, banana, cherry
### print(replace_2)                    ### ringo, ringo, ringo
### print(replace_3)                    ### azazacddeee
### print(replace_4)                    ### azzzazzzacddeee
### print(replace_5)                    ### azzcddeee

###############################################################################

上記のPythonプログラムは、文字列の操作に関する様々な関数を示しています。

  • rfind(): 指定した文字列の位置を逆方向から検索します。
  • rindex(): 指定した文字列の位置を逆方向から検索します。rfind()と同様ですが、文字列が見つからなかった場合はValueErrorを返します。
  • partition(): 指定した文字列を検索し、その文字列を中心に2つのタプルを返します。
  • rpartition(): partition()と同様ですが、文字列を逆方向から検索します。
  • count(): 指定した文字列の出現回数をカウントします。
  • isalpha(): 文字列がアルファベットのみで構成されているかどうかをチェックします。
  • islower(): 文字列がすべて小文字で構成されているかどうかをチェックします。
  • isupper(): 文字列がすべて大文字で構成されているかどうかをチェックします。
  • isidentifier(): 文字列が有効な識別子であるかどうかをチェックします。
  • isdecimal(): 文字列が10進数であるかどうかをチェックします。
  • isdigit(): 文字列が数字であるかどうかをチェックします。
  • isnumeric(): 文字列が数字であるかどうかをチェックします。
  • isalnum(): 文字列がアルファベットまたは数字で構成されているかどうかをチェックします。
  • istitle(): 文字列がタイトルケースであるかどうかをチェックします。
  • isprintable(): 文字列が印刷可能な文字だけで構成されているかどうかをチェックします。
  • isspace(): 文字列が空白のみで構成されているかどうかをチェックします。
  • encode(): 文字列を指定されたエンコーディングでエンコードします。
  • decode(): 文字列を指定されたエンコーディングでデコードします。
  • expandtabs(): 文字列内のタブをスペースに変換します。
  • split(): 文字列を指定された区切り文字で分割してリストに変換します。
  • rsplit(): 右から分割します。
  • splitlines(): 改行文字で分割してリストに変換します。
  • join(): イテラブルを指定の区切り文字で連結して文字列に変換します。
  • translate(): 文字列内の一部の文字列を、指定した文字列に置き換えます。
  • replace(): 文字列内の一部の文字列を、指定した文字列に置き換えます。

参考リンク … Reference Link