Hướng dẫn substring python w3schools
StringsStrings in python are surrounded by either single quotation marks, or double quotation marks. Show 'hello' is the same as "hello". You can display a string literal with the Assign String to a VariableAssigning a string to a variable is done with the variable name followed by an equal sign and the string: Multiline StringsYou can assign a multiline string to a variable by using three quotes: ExampleYou can use three double quotes: a = """Lorem ipsum dolor sit amet, Try it Yourself » Or three single quotes: Example a = '''Lorem ipsum dolor sit amet, Try it Yourself » Note: in the result, the line breaks are inserted at the same position as in the code. Strings are ArraysLike many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. ExampleGet the character at position 1 (remember that the first character has the position 0): a = "Hello, World!" Try it Yourself » Looping Through a StringSince strings are arrays, we can loop through the characters in a string, with a ExampleLoop through the letters in the word "banana": for x in "banana": Try it Yourself » Learn more about For Loops in our Python For Loops chapter. String LengthTo get the length of a string, use the ExampleThe a = "Hello, World!" Try it Yourself » Check StringTo check if a certain phrase or character is present in a string, we can use the keyword
ExampleCheck if "free" is present in the following text: txt = "The best things in life are free!" Try it Yourself » Use it in an ExamplePrint only if "free" is present: txt = "The best things in life are free!" Try it Yourself » Learn more about If statements in our Python If...Else chapter. Check if NOTTo check if a certain phrase or character is NOT present in a string, we can use the keyword ExampleCheck if "expensive" is NOT present in the following text: txt = "The best things in life are free!" Try it Yourself » Use it in an Exampleprint only if "expensive" is NOT present: txt = "The best things in life are free!" Try it Yourself » Python has a set of built-in methods that you can use on strings. Note: All string methods returns new values. They do not change the original string.
Note: All string methods returns new values. They do not change the original string. Learn more about strings in our Python Strings Tutorial. |