Python string introduction:
In this article, we’re going to look at strings. So a string is everything that goes inside quotes, “Hello World “.
print ("This is python Tutorial") This is a Python Tutorial
print('This is python Tutorial') This is a Python Tutorial
If you observe two screenshots either you use double quotes or you can use a single quote that works. Strings can be represented in Python source code in several ways:
- In simple ( ‘ ) and double ( ” ) quotation marks.
- In triple double ( “” ” ) or simple ( ” ‘ ) quotes.
Assigning strings to Variables:
Strings can be stored in variables and you can print those variables.
>>> var1= "Hello World" >>> Var2= "Hi,you there" >>> print(var1) Hello World >>> print(Var2) Hi,you there
How to print multiple lines of strings? See below how can do these?
>>> var="""This is python Tutorial ... Today we are going to talk all about strings ... and we will also look some build in functions""" >>> print(var) This is python Tutorial Today we are going to talk all about strings and we will also look some build in functions >>>
So far this is how you initialize or how you declare your strings in Python.
How Python stores strings:
Like all languages, Python strings are also indexed starting from zero but Python also has a very unique indexing system.
Indexing is a very important concept not only with strings but with all the data type that we’ll be looking at later such as lists, tuples, and dictionaries.
Let’s say you have a string called “PYTHON” and assigned to a variable called sample, now we will see how these stores in python.
>>> sample = “PYTHON”
So far seen in all programming languages you start with 0 so P is at 0th index then we have 1 2 3 4 5. So n is at the 5th index now.
The good thing about python is it also provides with negative indexing, negative indexing means you can go ahead and see the last element of the string by typing -1, so n is minus 1 o is -2 h is -3 and so on.
So normal indexing starts from 0, so P is at index 0 whereas the negative indexing when you are referring from backward it starts from -1, Remember it’s not -0 on the reverse order.
So you would ask why this is useful? Well, this allows you to extract certain parts from a string and there is a certain notation to do that you’d want to access the string.
Python string processing:
Remove the space :
str.strip (): delete the specified characters on both sides of the string, the brackets are written to the specified characters, the default is a space.
>>> x=' welcome ' >>> y=x.strip() >>> print(y) welcome
Str.lstrip (): delete the specified character to the left of the string, the specified characters are written in parentheses, the default is a space
>>> x=' welcome ' >>> y=x.lstrip() >>> print(y) welcome #The space on the right may not be obvious.
Str.rstrip (): delete the specified character to the right of the string, the default is a space.
>>> x=' welcome ' >>> y=x.rstrip() >>> print(y) welcome
Copy the string:
>>> x='hi there' >>> x=y >>> print(x,y) hi there hi there
+: Concatenate 2 strings >>> x='hi ' >>> y='there' >>> print(a+b) hi there
Note: This method is also called “the evil plus sign”, because using the plus sign to connect 2 strings will call the static function string_concat(register PyStringObject *a , register PyObject * b), in this function will open a piece of size is a +b memory and storage unit, then copy the a, b string into it. If n strings are connected, then n-1 memory is opened, which is very resource intensive.
Str.join: connect 2 strings, you can specify the connection symbol (for join, the reader can view some related information by himself)
>>> x='welcome ' >>> y='####' >>> x.join(y) '#welcome #welcome #welcome #'
Find the string:
#str.index and str.find have the same function. The difference is that find() fails to return -1, which does not affect the program. Generally, find!=-1 or find>-1 is used as the judgment condition.
Str.index: Check whether the substring string is included in the string, and the range can be specified.
x='hi world' >>> x.index('l') 2 >>> x.index('x') Traceback (most recent call last): File "<pyshell#40>", line 1, in <module> A.index('x') ValueError: substring not found
Str.find: Detects whether the substring str is included in the string, and can specify the range.
>>> x='hi there' >>> y.find('l') 2 >>> x.find('x') -1
Str.cmp: Compares two objects and returns an integer based on the result. X< Y, the return value is a negative number, and the value returned by X>Y is a positive number.
#python3 has no such method, the official document is written as follows:
The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__( .), and other rich comparisons as needed (If you really need the cmp () functionality, you could use the expression (a> b) – (a <b) as the equivalent for cmp (a, b)).
the effect that The cmp() function has “away”. If you really need the cmp() function, you can use the expression (a > b) – (a < b) instead of cmp(a,b)
>>> x=100 >>> y=80 >>> cmp(x,y) 1
Whether to include the specified string:
in |not in >>> a='hello world' >>> 'hello' in a True >>> '123' not in a True
>>> a='hello world' >>> print(len(a)) 11
Letter case conversion in string:
S.lower() #convert to lowercase >>> a='Hello World' >>> print(a.lower()) Hello world
S.upper() #convert to uppercase
>>> a='Hello World' >>> print(a.upper()) HELLO WORLD
S.swapcase() #Cold and write swap
>>> a='Hello World' >>> print(a.swapcase()) hELLO wORLD
S.capitalize() # initial capitalization
>>> a='Hello World' >>> print(a.capitalize()) Hello world
Put the string into the center position to specify the length and the characters on both sides of the position:
str.center() >>> a='hello world' >>> print(a.center(40,'*')) **************hello world***************
>>> a='hello world' >>> print(a.count('l')) 3
String test, judgment function, this type of function is not in the string module, these functions return a Boolean value:
S.startswith(prefix[,start[,end]]) #Do you want to start with prefix? S.endswith(suffix[,start[,end]]) #End with suffix S.isalnum() # is all letters and numbers and has at least one character S.isalpha() # is all letters and has at least one character S.isdigit() # is all numbers and has at least one character S.isspace() # is all blank characters and has at least one character Whether the letters in S.islower() #S are all lowercase Is the letter in S.isupper() #S uppercase? S.istitle() #S is the first letter capitalized
Str = '0123456789' Print str[0:3] # intercept the first to third characters Print str[:] # intercept all characters of the string Print str[6:] # intercept the seventh character to the end Print str[:-3] # intercept from the beginning to the third last character Print str # intercept the third character Print str[-1] # intercept the first character of the last Print str[::-1] #Create a string that is the reverse of the original string order Print str[-3:-1] #Cut the third digit from the last digit and the character before the first digit from the last Print str[-3:] # intercept the third to the end Print str[:-5:-3] #reverse sequence interception, intercept between the fifth last digit and the third last digit
The important thing to emphasize here is that the string object is immutable, which means that you cannot change a part of the character after creating a string in python. Any of the above functions will change a string and will return a new string. The original string has not changed.
Python String iteration:
Just see below programme to understand more these.
welcome = "Hello World" print(welcome) for character in welcome: print(character)
let’s consider the above computer program, the first line is welcome is assigned hello world, what this will do it will bind the identifier to welcome to a string object that contains the string hello world. The next line print welcome will actually put to the screen the string hello world. On the next line an iteration construct often referred to as a repetition construct, because what’s going to happen this particular line here is going to be executed more than once because we’re going to be in a loop.