Basic String Operations
Strings are bits of text. They can be defined as anything between quotes:
string = "Hello world!" string2 = 'Hello world!'
As you can see, the first thing you learned was printing a simple sentence. This sentence was stored by Python as a string. However, instead of immediately printing strings out, we will explore the various things you can do to them. You can also use single quotes to assing a string. However, you will face problems if the value to be assigned itself contains single quotes.For example to assign the string in these bracket(single quotes are ' ') you need to use double quotes only like this
print "single quotes are ' '" string = "Hello world!" print len(string)
That prints out 12, because "Hello world!" is 12 characters long, including punctuation and spaces.
string = "Hello world!" print string.index("l")
That prints out 2, because the location of the first occurrence of the letter "l" is 2 characters away from the first character. Python (and most other programming languages) start counting things at 0 instead of 1. So the index of "l" is 1.
This prints a slice of the string, starting at index 3, and ending at index 6. But why 6 and not 7 ? it makes doing math inside those brackets easier.
Check Occurence of String
Checks if string starts with "Hello"
Checks if string ends with "asdfasdfasdf"
Explode or Split the string
splitWords = string.split(" ")
This splits the string into a bunch of strings grouped together in a list. Since this example splits at a space, the first item in the list will be "Hello", and the second will be "world!".
There are more in python. We will soon launch course only for strings soon.
Related Results :
- Related Posts are generally User Blog posts.
- or Other tutorials from other networks of w3clan.com.
- Any registered user can create related posts based on search term tags.