This article is written by a fledgling engineer who has been studying programming for about two months for the purpose of output. After biting ruby and js, I became interested in the trend python, so I started learning. This time I will write an article about character strings. This is a poor article, but I would appreciate it if you could point out any points that interest you! This article is based on the assumption that python3 and anaconda are installed on macOS.
The string has an index number.
sample.py
sample = "abcdefghi"
#↑↑↑↑↑↑↑↑↑
#012345678 When counting from before
#-{987654321}When counting after
The index number of the character string counts the first character from 0. It is easy to make a mistake, so be careful. When counting from the back, start with -1.
>>>sample = "abcdefghi"
Use [] to retrieve c with index number 2.
Interpreter
>>>sample = "abcdefghi"
>>>sample [2]
'c'
I was able to extract c from the string. Next, let's take out c using the index number when counting from the back.
Interpreter
>>>sample = "abcdefghi"
>>>sample [−7]
'c'
I was able to retrieve the string safely, but there is one caveat. It is Kano to extract a character string by index number, but it cannot be rewritten.
Interpreter
>>>sample = "abcdefghi"
>>>sample [−7] = "j"
File "<stdin>", line 1
sample [−7] = "j"
^
SyntaxError: invalid character in identifier
If you try to replace sample [-7] with "j" like this, you will get an error.
It is also possible to extract a character string by specifying a range using [].
Interpreter
>>>sample = "abcdefghi"
>>>sample[1:4]
#String[Start number:End number]
'bcd'
In the above, index numbers 1 a to 4 d are selected and extracted. The start number and end number can be omitted.
Interpreter
>>>sample = "abcdefghi"
>>>sample[:4]
#String[:End number]
'abcd'
In this case, the range from the beginning of the character string to the number 4 is specified.
Interpreter
>>>sample = "abcdefghi"
>>>sample[1:]
#String[Start number:]
'bcdefghi'
In this case, you can specify the range from number 1 to the end.
This is the end of this article. Even if you know that the index number of a character string counts the first character from 0, it is easy to make a mistake.
Previous article → https://qiita.com/shin12032123/items/a8cc0d7612259683562e
Recommended Posts