21
NovWhat are Strings in Python? Learn to Implement Them.
As a learner or programmer, manipulating and creating strings is an important skill to have. Whether you're formatting data for printing or configuring personalized welcome messages for your users, being able to write clean code with strings makes all the difference in quality development. Thankfully mastering string manipulation doesn't have to be a difficult task if you know how Python handles String values it can be pretty easy through a Python certification course. In this article, we'll show you everything you need to know about working with Strings in the Python language
What are Strings in Python?
Strings in Python are an integral part of the programming language and are used to represent text data. Strings are immutable so they cannot be changed once they are created. This means strings can be stored in the same way each time they’re used, making them more efficient for developers. In Python, strings can be manipulated in a variety of ways with built-in functions such as upper() and lower(). Additionally, strings can also support regular expressions for string matching and replacement. Due to the feature of versatility strings in Python offer developers many different options when dealing with textual data.
Example
var1 = 'Hello World!'
var2 = "Python Programming"
Read More - 50 Python Interview Questions and Answers
Accessing String Value in Python
Accessing string value in Python programming language is easy to do, and can be an invaluable tool when working on larger programming projects. Python has a built-in setup for accessing the characters in each string, known as 'slicing'. With the slicing syntax, anyone can “extract” or “slice” different parts of the string in order to get specific values. Accessing string values also opens up applications such as changing the capitalization of letters within a word and more.
Example
var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
Output
var1[0]: H
var2[1:5]: ytho
Updating Strings
Example
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
Output
Updated String :- Hello Python
Read More - Python Developer Salary in India
Python escape characters
Backslash notation | Hexadecimal character | Description |
\a | 0x07 | Bell or alert |
\b | 0x08 | Backspace |
\cx | Control-x | |
\C-x | Control-x | |
\e | 0x1b | Escape |
\f | 0x0c | Formfeed |
\n | 0x0a | Newline |
\nnn | Octal notation, where n is in the range of 0.7 | |
\r | 0x0d | Carriage return |
\s | 0x20 | Space |
\t | 0x09 | Tab |
\v | 0x0b | Vertical tab |
\x | Character x | |
\xnn | Hexadecimal notation, where n is in the range 0.9, a.f, or A.F |
String Special Operators in python
Operator | Description | Example |
+ | Concatenation - It adds values on either side of the operator | a + b will give HelloPython |
* | Repetition - It creates new “strings”, concatenating multiple copies of the same string | a*2 will give -HelloHello |
[] | Slice - This operator gives the character from the given index | a[1] will give e |
[ : ] | Range Slice - It gives the characters from the given range | a[1:4] will give ell |
in | Membership - This particular operator returns “true” if a character exists in the given string | H in a will give 1 |
not in | Membership - It returns “true” if a character does not exist in the given string | M not in a will give 1 |
r/R | Raw String - This particular operator suppresses the actual meaning of “Escape characters”. The syntax for raw strings is the same as for any normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. | print r'\n' prints \n and print R'\n'prints \n |
% | Format - Performs String formatting | Explain in the following section |
String formatting Operator in Python
String formatting operators in Python are powerful tools that allow developers to save valuable time. Rather than manually replacing strings, a string formatting operator can automate the entire process with just a few lines of code. String formatting operations can also improve the readability and maintainability of code, which is especially helpful if there are many variables or strings to be replaced
Example in the Python Compiler
print "My name is %s and weight is %d kg!" % ('Urmi', 45)
Output
My name is Urmi and weight is 45 kg!
Here is the list of a complete set of symbols that can be used along with % −Format Symbol | Conversion |
%c | character |
%s | string conversion via str() prior to formatting |
%i | signed decimal integer |
%d | signed decimal integer |
%u | unsigned decimal integer |
%o | octal integer |
%x | hexadecimal integer (lowercase letters) |
%X | hexadecimal integer (UPPERcase letters) |
%e | exponential notation (with lowercase 'e') |
%E | exponential notation (with UPPERcase 'E') |
%f | floating point real number |
%g | the shorter of %f and %e |
%G | the shorter of %f and %E |
Other supported symbols and their functionality are listed in the following table −
Symbol | Functionality |
* | the argument specifies width or precision |
- | left justification |
+ | display the sign |
<sp> | leave a blank space before a positive number |
# | add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' was used. |
0 | pad from left with zeros (instead of spaces) |
% | '%%' leaves you with a single literal '%' |
(var) | mapping variable (dictionary arguments) |
m.n. | m is the minimum total width and n is the number of digits to display after the decimal point (if appl.) |
Unicode String
Example
print 'Hello, world!'
Output
Hello, world!
Built in string methods in python with example
Sr.No. | Methods | Description |
1. | capitalize() | Capitalizes the first letter of the string |
2. | center(width, fillchar) | Returns a space-padded string with the original string centered to a total of width columns. |
3. | count(str, beg= 0,end=len(string)) | Counts how many times str occurs in a string or in a substring of string if starting index beg and ending index end are given. |
4. | decode(encoding='UTF-8',errors='strict') | Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. |
5. | encode(encoding='UTF-8',errors='strict') | Returns encoded string version of string; on error, default is to raise a ValueError unless errors are given with 'ignore' or 'replace' |
6. | endswith(suffix, beg=0, end=len(string)) | Determines if a string or a substring of string (if starting index begs and ending index end are given) ends with a suffix; returns true if so and false otherwise. |
7. | expandtabs(tabsize=8) | Expands tabs in the string to multiple spaces; defaults to 8 spaces per tab if tab size not provided |
10. | find(str, beg=0 end=len(string)) | Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise. |
11. | index(str, beg=0, end=len(string)) | Same as find(), but raises an exception if str is not found. |
12. | isalnum() | Returns true if the string has at least 1 character and all characters are alphanumeric and false otherwise. |
13. | isalpha() | Returns true if the string has at least 1 character and all characters are alphabetic and false otherwise. |
14. | isdigit() | Returns true if the string contains only digits and false otherwise. |
15. | islower() | Returns true if the string has at least 1 cased character and all cased characters are in lowercase and false otherwise |
16. | istitle() | Returns true if the string is properly "titlecased" and false otherwise |
17. | isupper() | Returns true if the string has at least one cased character and all cased characters are in uppercase and false otherwise. |
18. | join(seq) | Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string. |
19. | len(string) | Returns the length of the string |
20. | ljust(width[, fillchar]) | Returns a space-padded string with the original string left-justified to a total of width columns. |
21. | lower() | Converts all uppercase letters in a string to lowercase. |
22. | lstrip() | Removes all leading whitespace in string. |
23. | maketrans() | Returns a translation table to be used in the translate function. |
24. | max(str) | Returns the max alphabetical character from the string str. |
25. | min(str) | Returns the min alphabetical character from the string str. |
26. | replace(old, new [, max]) | Replaces all occurrences of old in the string with new or at most max occurrences if max is given. |
27. | rfind(str, beg=0,end=len(string)) | Same as find(), but search backward in string. |
28. | rindex( str, beg=0, end=len(string)) | Same as index(), but search backward in string. |
29. | rjust(width,[, fillchar]) | Returns a space-padded string with the original string right-justified to a total of width columns. |
30. | rstrip() | Removes all trailing whitespace of string. |
31. | split(str="", num=string.count(str)) | Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given. |
32. | splitlines( num=string.count('\n')) | Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed. |
33. | startswith(str, beg=0,end=len(string)) | Determines if a string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise. |
34. | strip([chars]) | Performs both lstrip() and rstrip() on the string. |
35. | swapcase() | Inverts case for all letters in the string. |
36. | title() | Returns "titlecased" version of the string, that is, all words begin with uppercase and the rest are lowercase. |
37. | translate(table, deletechars="") | Translates string according to translation table str(256 chars), removing those in the del string. |
38. | upper() | Converts lowercase letters in a string to uppercase. |
39. | zfill (width) | Returns original string left padded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero). |
40. | isdecimal() | Returns true if a Unicode string contains only decimal characters and false otherwise. |