Status : Completed
A 'string' is simply a list of characters in order. A character is anything you can type on the keyboard in one keystroke, like a letter, a number, or a backslash. For example, "hello" is a string. It is five characters long h, e, l, l, o. Strings can also have spaces: "hello world" contains 11 characters, including the space between "hello" and "world". There are no limit’s to the number of characters you can have in a string, you can have anywhere from one to a million or more. You can even have a string that has 0 characters, which is usually called "the empty string."
There are three ways you can declare a string in Python, single quotes ('), double quotes ("), and triple quotes ("""). In all cases, you start and end the string with your chosen string declaration. When we use triple quotes, strings can span several lines without using the escape character. For example;
Single Quoted String:
>>> print 'Hello, My name is James Franco' Hello, My name is James Franco
Double Quotes String:
>>> print "Hello, My name is James Franco" Hello, My name is James Franco
Triple Quoted String:
>>> print """Hello, My name is James Franco ... and i am 25 years old ... i like football ... """ Hello, My name is James Franco and i am 25 years old i like football
If we want to create unicode strings, we add a u/U character at the beginning of the text.
>>> x = u'u043au0443u043bu0438u0441u0430u043cu0438 u0438u043du0442u0435u0440u0432u044cu044e u0410u0432u0434u043eu0442u044cu0438 u0421u043cu0438u0440u043du043eu0432u043eu0439 u0434u043bu044f HELLO!' >>> print x кулисами интервью Авдотьи Смирновой для HELLO!
String Operators:
Following are the string operators with respective examples in python;
'*' Repetition, Creates new strings, concatenating multiple copies of the same string.
>>> x = "Doom" >>> x*3 'DoomDoomDoom'
'[]' Slice, Gives the character from the given index.
>>> x = 'Doom' >>> x[3] 'm'
'[:]' Range Slice, Gives the characters from the given range.
>>> x = 'Doom' >>> x[1:3] 'oo'
'in' Membership, Returns true if a character exists in the given string.
>>> x = 'Doom' >>> 'm' in x True
'not in' Membership, Returns true if a character does not exist in the given string.
>>> x = 'Doom' >>> 'a' not in x True >>> 'D' not in x False
Python Builtin Methods for string:
Python has many builtin methods for string which are described below with example. As we have learned in "Python help and dir post"(Link), you can find all methods using dir() function. For Example: x = 'Hello' dir(x) will give you list of builtin methods for string.
capitalize() : Capitalizes first letter of string. If string consists of multiple words or string has capital letters other than except first letter of string, it will capitalize first letter of string and un-capitalize the other letters in string.
Example: >>> x = "hello" >>> x.capitalize() 'Hello'
>>> x = "Hello How Are You ?" >>> x.capitalize() 'Hello how are you ?'
center() : The method center() returns centered in a string of length width. Padding is done using the specified fill-char. Default filler is a space.
In example below '18', '10' is width and '*', '#' is fill-char.
Example:
>>> x = "Hello..." >>> x.center(18, '*') '*****Hello...*****' >>> x.center(18) ' Hello... ' >>> x.center(10, '#') '#Hello...#'
count() : The method count() returns the number of occurrences of substring in the range start & end.
Example:
>>> x = "Hello...Hi" >>> x.count('H', 0, 12) 2 >>> x.count('He', 0, 12) 1 >>> x.count('H') 2
encoding() : The method encode() returns an encoded version of the string. Default encoding is the current default string encoding.
Example:
>>> x = "Hello..." >>> x.encode('base64') 'SGVsbG8uLi4=n'
decoding() : The method decode() decodes the string using the codec registered for encoding. It defaults to the default string encoding.
Example:
>>> x = "Hello..." >>> x = x.encode('base64') >>> x.decode('base64') 'Hello...'
endswith() : The method endswith() returns True if the string ends with the specified suffix, otherwise return False optionally restricting the matching with the given range start & end.
Example:
>>> x = "Hello" >>> x.endswith('o') True >>> x.endswith('j') False >>> x = "Hello, how are you" >>> x.endswith('you') True >>> x.endswith('are') False
expandtabs() : The method expandtabs() returns a copy of the string in which tab characters i.e. 't' have been expanded using spaces, optionally using the given tabsize (default 8).
Example:
>>> x = "Hello,tHow are you" >>> print x Hello, How are you >>> x.expandtabs(10) 'Hello, How are you' >>> x.expandtabs(15) 'Hello, How are you'
find() : The method find() determines if string str occurs in string, or in a substring of string, if starting index and ending index end are given will determines string in given range. This method returns index if found and -1 otherwise.
Example:
>>> x = "Hello, How are you" >>> x.find('o') 4 >>> x.find('o', 7, 10) 8 >>> x.find('how') -1 >>> x.find('How') 7
index() : This method is same as find(), but raises an exception if sub is not found. This method returns index if found otherwise raises an exception if str is not found.
Example:
>>> x = "Hello, How are you" >>> x.index('h') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> x.index('H') 0 >>> x.index('How') 7
isalnum() : The method isalnum() checks whether the string consists of alphanumeric characters.This method returns true if all characters in the string are alphanumeric and there is at least one character, false otherwise.
Example:
>>> x = "Hello" >>> x.isalnum() True >>> x = "Hello5" >>> x.isalnum() True >>> x = "Hello 5" >>> x.isalnum() False
isalpha() : The method isalpha() checks whether the string consists of alphabetic characters only. This method returns true if all characters in the string are alphabetic and there is at least one character, false otherwise.
Example:
>>> x = "Hello !!!" >>> x.isalpha() False >>> x = "Hello" >>> x.isalpha() True >>> x = "Hello54" >>> x.isalpha() False
isdigit() : The method isdigit() checks whether the string consists of digit’s only. This method returns true if all characters in the string are digit’s and there is at least one character, false otherwise.
Example:
>>> x = "Hello" >>> x.isdigit() False >>> x = "Hello43" >>> x.isdigit() False >>> x = "443" >>> x.isdigit() True >>> x = "Hello 43" >>> x.isdigit() False
islower() : The method islower() checks whether all the case-based characters (letters) of the string are lowercase. This method returns true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
Example:
>>> x = "Hello" >>> x.islower() False >>> x = "hello" >>> x.islower() True >>> x = "hello How are you ?" >>> x.islower() False >>> x = "hello how are you ?" >>> x.islower() True
isspace() : The method isspace() checks whether the string consists of whitespace.
This method returns true if there are only whitespace characters in the string and there is at least one character, false otherwise.
Example:
>>> x = "Hello Hi" >>> x.isspace() False >>> x = " " >>> x.isspace() True
istitle() : The method istitle() checks whether all the case-based characters in the string following non-casebased letters are uppercase and all other case-based characters are lowercase. This method returns true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones.It returns false otherwise.
Example:
>>> x = "Hello, How Are You ?" >>> x.istitle() True >>> x = "Hello, How are you ?" >>> x.istitle() False
isupper() : The method isupper() checks whether all the characters (letters) of the string are uppercase. This method returns true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
Example:
>>> x = "HELLO, HOW ARE YOU ?" >>> x.isupper() True >>> x = "HELLO, How Are You ?" >>> x.isupper() False
join() : The method join() returns a string. Which is the concatenation of the strings.
Example:
>>> x = "Hello World" >>> y = "," >>> y.join(x) 'H,e,l,l,o, ,W,o,r,l,d' >>> x = "abcdef" >>> y = "-" >>> y.join(x) 'a-b-c-d-e-f'
len() : The method len() returns the length of the string.
Example:
>>> x = "HELLO, How Are You ?" >>> len(x) 20 >>> x = "abcdef" >>> len(x) 6
ljust() : This method returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
Example:
>>> x = "HELLO, How Are You ?" >>> x.ljust(50, 'D') 'HELLO, How Are You ?DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD' >>> x.ljust(10, 'D') 'HELLO, How Are You ?'
lower() : This method returns a copy of the string in which all characters have been lowercased.
Example:
>>> x = "HELLO, HOW ARE YOU ?" >>> x.lower() 'hello, how are you ?'
lstrip() : This method returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters).
Example:
>>> x = " HELLO, HOW ARE YOU ?" >>> x.lstrip() 'HELLO, HOW ARE YOU ?' >>> x = "XXXXXXXXXXXXXXHELLO, HOW ARE YOU ?" >>> x.lstrip('X') 'HELLO, HOW ARE YOU ?' >>> x = "XXXXXXXXXXXXXXHELLO, HOW ARE YOU ?XXXX" >>> x.lstrip('X') 'HELLO, HOW ARE YOU ?XXXX'
partition() : Search for the separator sep in S, and return the part before it, the separator it’self, and the part after it. If the separator is not found, return S and two empty strings.
Example:
>>> x = "HELLO, HOW ARE YOU ?" >>> x.partition(',') ('HELLO', ',', ' HOW ARE YOU ?') >>> x.partition('?') ('HELLO, HOW ARE YOU ', '?', '') >>> x.partition('#') ('HELLO, HOW ARE YOU ?', '', '')
replace() : The method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
Example:
>>> x = "Where are you?, Where is your Friend?" >>> x.replace("Where", "How") 'How are you?, How is your Friend?' >>> x.replace("Where", "How", 1) 'How are you?, Where is your Friend?'
rfind() : The method rfind() returns the last index where the substring str is found, or -1 if no such index exists.
Example:
>>> x = "HELLO, HOW ARE YOU ?" >>> x.rfind('you') -1 >>> x.rfind('YOU') 15 >>> x.rfind('Y') 15 >>> x.rfind('A') 11 >>> x.rfind('A', 1, 7) -1
rindex() : The method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists.
Example:
>>> x = "HELLO, HOW ARE YOU ?" >>> x.rindex('ARE') 11 >>> x.rindex('YOU') 15 >>> x.rindex('Are') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
rjust() : The method rjust() returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
Example:
>>> x = "HELLO, HOW ARE YOU ?" >>> x.rjust(20, '*') 'HELLO, HOW ARE YOU ?' >>> x.rjust(30, '*') '**********HELLO, HOW ARE YOU ?'
rstrip() : The method rstrip() returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters).
Example:
>>> x = "*** HELLO, HOW ARE YOU ? ***" >>> x.rstrip('*') '*** HELLO, HOW ARE YOU ? '
split() : The method split() returns a list of all the words in the string, using str as the separator (split’s on all whitespace if left unspecified), optionally limiting the number of split’s to num.
Example:
>>> x = "Where are you?, Where is your Friend?" >>> x.split() ['Where', 'are', 'you?,', 'Where', 'is', 'your', 'Friend?'] >>> x.split(',') ['Where are you?', ' Where is your Friend?'] >>> x.split('Where') ['', ' are you?, ', ' is your Friend?']
splitlines() : The method splitlines() returns a list with all the lines in string, optionally including the line breaks (if num is supplied and is true).
Example:
>>> x = "HellonHow are you?nWhere i your friend?" >>> x.splitlines() ['Hello', 'How are you?', 'Where i your friend?']
startswith() : The method startswith() checks whether string starts with str, optionally restricting the matching with the given range start & end.
Example:
>>> x = "Where are you?, Where is your Friend?" >>> x.startswith('Where') True >>> x.startswith('where') False >>> x.startswith('are') False
strip() : The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
Example:
>>> x = "*****Where are you?, Where is your Friend?******" >>> x.strip('*') 'Where are you?, Where is your Friend?'
swapcase() : The method swapcase() returns a copy of the string in which all the characters have had their case swapped.
Example:
>>> x = "where are you?, where is your friend?" >>> x.swapcase() 'WHERE ARE YOU?, WHERE IS YOUR FRIEND?' >>> x = "HELLO WORLD...!!!" >>> x.swapcase() 'hello world...!!!'
title() : The method title() returns a copy of the string in which first characters of all the words are capitalized.
Example:
>>> x = "where ar e you?, where is your friend?" >>> x.title() 'Where Are You?, Where Is Your Friend?' >>> x = "hello world...!!!" >>> x.title() 'Hello World...!!!'
translate() : The method translate() returns a copy of the string in which all characters have been translated using table (constructed with the maketrans() function in the string module), optionally deleting all characters found in the string.
Example:
>>> from string import maketrans >>> x = "where are you?, where is your friend?" >>> a = "waifd" >>> b = "*****" >>> c = maketrans(a, b) >>> x.translate(c) '*here *re you?, *here *s your *r*en*?' >>> x.translate(c, 'h') '*ere *re you?, *ere *s your *r*en*?'
upper() : The method upper() returns a copy of the string in which all characters have been uppercased.
Example:
>>> x = "where are you?, where is your friend?" >>> x.upper() 'WHERE ARE YOU?, WHERE IS YOUR FRIEND?'
zfill() : The method zfill() pads string on the left with zeros to fill width.
Example:
>>> x = "where are you?, where is your friend?" >>> x.zfill(30) 'where are you?, where is your friend?' >>> x.zfill(40) '000where are you?, where is your friend?' >>> x.zfill(50) '0000000000000where are you?, where is your friend?'
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018