python string

Python String-:  Strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.For example

str=" welcome in python"

String Method in Python-: Most of the Python string methods are built into the standard Python string class so all string objects have them automatically. The standard string module also contains some useful constants.

Most string methods are attached to the string object they operate on by a dot (.), as in x.upper(). They are  prep-ended with the string object followed by a dot. Because strings are immutable the string methods are used only to obtain their return value and do not modify the string object they are attached to in any way.

The split and join string methods-: Anyone who works with strings is almost certain to find the split and join methods invaluable. They are the inverse of one another. split returns a list of sub strings in the string and join takes a list of strings and puts them together to form a single string with the original string between each element. split uses white-space as the delimiter to the strings it is splitting but we can change that behaviour via an optional argument.

String concatenation using + is useful but not efficient for joining large numbers of strings into a single string  because each time + is applied a new string object is created. The previous “Hello World” example produces two string objects one of which is immediately discarded. A better option is to use the join function. as like here

>>> " ".join(["join", "puts", "spaces", "between", "elements"])
'join puts spaces between elements'

By changing the string used to join we can put anything we want between the joined strings as like

>>> "::".join(["Separated", "with", "colons"])
'Separated::with::colons'

we can even use an empty string, “”, to join elements in a list as like

>>> "".join(["welcome", "by", "netnic"])
'welcomebynetnic'

The most common use of split is probably as a simple parsing mechanism for string-delimited records stored in text files.  splits are on any white-space, not just a single space character, but we can also tell it to split on a particular sequence by passing it an optional argument as like …

>>> x = "You\t\t can have tabs\t\n \t and newlines \n\n " \
               "mixed in"
>>> x.split()
['You', 'can', 'have', 'tabs', 'and', 'newlines', 'mixed', 'in']
>>> x = "Mississippi"
>>> x.split("ss")
['Mi', 'i', 'ippi']

It is very useful to permit the last field in a joined string to contain arbitrary text perhaps including sub-strings that may match what split splits on when reading in that data. we can do this by specifying how many splits split should perform when it is generating its result via an optional second argument. If we  specify n splits, split goes along the input string until it has performed n splits (generating a list with n+1 sub-strings as elements) or until it runs out of string. Here are some examples of this

>>> x = 'a b c d'
>>> x.split(' ', 1)
['a', 'b c d']
>>> x.split(' ', 2)
['a', 'b', 'c d']
>>> x.split(' ', 9)
['a', 'b', 'c', 'd']

Converting strings to numbers in python-: We can use the functions int and float to convert strings to integer or floating-point numbers.If we  passed a string that can not  be interpreted as a number of the given type these functions raise a ValueError exception.  For example

>>> float('123.456')
123.456
>>> float('xxyy')
Traceback (innermost last):
 File "<stdin>", line 1, in ?
ValueError: could not convert string to float: 'xxyy'
>>> int('3333')
3333
>>> int('123.456')                                             1
Traceback (innermost last):
 File "<stdin>", line 1, in ?
ValueError: invalid literal for int() with base 10: '123.456'
>>> int('10000', 8)                                            2
4096
>>> int('101', 2)
5
>>> int('ff', 16)
255
>>> int('123456', 6)                                           3
Traceback (innermost last):
 File "<stdin>", line 1, in ?
ValueError: invalid literal for int() with base 6: '123456'

Can not have decimal point in integer.
Interprets 10000 as octal number
Can not interpret 123456 as base 6 number.

String Search in python-: The string objects provide several methods to perform simple string searches. There are some…

String search using The re module-: The re module also does string searching but in a far more flexible manner, using regular expressions. Rather than search for a single specified sub-string a re module search can look for a string pattern. we could look for sub-strings that consist entirely of digits.

The four basic string-searching methods are similar as  find, rfind, index, and rindex. A related method, count, counts how many times a sub-string can be found in another string. For example

>>> x = "Mississippi"
>>> x.find("ss")
2
>>> x.find("zz")
-1

Modifying strings-: We know that the Strings are immutable but string objects have several methods that can operate on that string and return a new string that is  a modified version of the original string. This provides much the same effect as direct modification for most purposes. we can find a more complete description of these methods in the documentation.

we can use the replace method to replace occurrences of sub-string (its first argument) in the string with newstring (its second argument). This method also takes an optional third argument as like this

>>> x = "Mississippi"
>>> x.replace("ss", "+++")
'Mi+++i+++ippi'

Modifying strings with list manipulations-: Strings are immutable objects, we have no way to manipulate them directly in the same way that we can manipulate lists. Although the operations that produce new strings (leaving the original strings unchanged) are useful for many things  sometimes we want to be able to manipulate a string as though it were a list of characters. In that case turn the string into a list of characters do whatever we want, and then turn the resulting list back into a string.

>>> text = "Hello, World"
>>> wordList = list(text)
>>> wordList[6:] = []                  1
>>> wordList.reverse()
>>> text = "".join(wordList)
>>> print(text)                        2
,olleH

Removes everything after comma
Joins with no space between

Useful methods and constants-: String objects also have several useful methods to report various characteristics of the string, such as whether it consists of digits or alphabetic characters  or is all uppercase or lowercase.

>>> x = "1234"
>>> x.isdigit()
True
>>> x.isalpha()
False
>>> x = "N"
>>> x.islower()
False
>>> x.isupper()
True

Common string operation list here

python string

string in pythonConverting From Object to String-: Python can be converted to some sort of a string representation by using the built-in repr function. Lists are the only complex Python data types. For example

 repr([1, 2, 3])
'[1, 2, 3]'
>>> x = [1]
>>> x.append(2)
>>> x.append([3, 4])
>>> 'the list x is ' + repr(x)
'the list x is [1, 2, [3, 4]]'

 

 

Leave a Comment