How To Add Letter To String Python
Python iii - Strings
Strings are among the nearly popular types in Python. We can create them simply past enclosing characters in quotes. Python treats single quotes the same equally double quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!' var2 = "Python Programming"
Accessing Values in Strings
Python does not support a character type; these are treated as strings of length one, thus also considered a substring.
To access substrings, employ the square brackets for slicing along with the index or indices to obtain your substring. For example −
#!/usr/bin/python3 var1 = 'Hello World!' var2 = "Python Programming" print ("var1[0]: ", var1[0]) impress ("var2[1:5]: ", var2[1:5])
When the higher up lawmaking is executed, it produces the following result −
var1[0]: H var2[1:v]: ytho
Updating Strings
You can "update" an existing string past (re)assigning a variable to some other string. The new value tin can be related to its previous value or to a completely different string birthday. For case −
#!/usr/bin/python3 var1 = 'Hello Earth!' print ("Updated String :- ", var1[:half-dozen] + 'Python')
When the above code is executed, it produces the following result −
Updated String :- Hello Python
Escape Characters
Following tabular array is a list of escape or not-printable characters that tin can be represented with backslash annotation.
An escape character gets interpreted; in a unmarried quoted every bit well as double quoted strings.
Backslash note | Hexadecimal character | Description |
---|---|---|
\a | 0x07 | Bong or alarm |
\b | 0x08 | Backspace |
\cx | Control-10 | |
\C-x | Command-10 | |
\east | 0x1b | Escape |
\f | 0x0c | Formfeed |
\One thousand-\C-x | Meta-Command-x | |
\n | 0x0a | Newline |
\nnn | Octal annotation, where due north is in the range 0.7 | |
\r | 0x0d | Carriage render |
\due south | 0x20 | Space |
\t | 0x09 | Tab |
\v | 0x0b | Vertical tab |
\x | Grapheme ten | |
\xnn | Hexadecimal notation, where n is in the range 0.ix, a.f, or A.F |
String Special Operators
Presume string variable a holds 'Hello' and variable b holds 'Python', and then −
Operator | Description | Example |
---|---|---|
+ | Concatenation - Adds values on either side of the operator | a + b volition give HelloPython |
* | Repetition - Creates new strings, concatenating multiple copies of the same string | a*2 will give -HelloHello |
[] | Slice - Gives the character from the given alphabetize | a[1] will give e |
[ : ] | Range Slice - Gives the characters from the given range | a[1:4] volition give ell |
in | Membership - Returns true if a graphic symbol exists in the given string | H in a volition give 1 |
not in | Membership - Returns true if a character does non exist in the given string | Chiliad not in a will requite 1 |
r/R | Raw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter of the alphabet "r," which precedes the quotation marks. The "r" can be lowercase (r) or capital letter (R) and must be placed immediately preceding the first quote mark. | impress r'\due north' prints \northward and print R'\northward'prints \n |
% | Format - Performs String formatting | See at next section |
Cord Formatting Operator
One of Python's coolest features is the string format operator %. This operator is unique to strings and makes upwards for the pack of having functions from C's printf() family. Post-obit is a simple example −
#!/usr/bin/python3 print ("My proper noun is %due south and weight is %d kg!" % ('Zara', 21))
When the to a higher place code is executed, it produces the following result −
My proper name is Zara and weight is 21 kg!
Hither is the list of consummate set up of symbols which can exist used along with % −
Sr.No. | Format Symbol & Conversion |
---|---|
1 | %c character |
2 | %s string conversion via str() prior to formatting |
iii | %i signed decimal integer |
4 | %d signed decimal integer |
5 | %u unsigned decimal integer |
6 | %o octal integer |
7 | %x hexadecimal integer (lowercase letters) |
8 | %Ten hexadecimal integer (UPPERcase letters) |
nine | %e exponential notation (with lowercase 'e') |
x | %East exponential note (with Uppercase 'East') |
eleven | %f floating point real number |
12 | %g the shorter of %f and %eastward |
13 | %One thousand the shorter of %f and %Due east |
Other supported symbols and functionality are listed in the post-obit tabular array −
Sr.No. | Symbol & Functionality |
---|---|
1 | * argument specifies width or precision |
2 | - left justification |
iii | + display the sign |
iv | <sp> get out a blank infinite before a positive number |
5 | # add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used. |
six | 0 pad from left with zeros (instead of spaces) |
vii | % '%%' leaves you with a single literal '%' |
8 | (var) mapping variable (dictionary arguments) |
9 | m.n. m is the minimum total width and north is the number of digits to display after the decimal point (if appl.) |
Triple Quotes
Python's triple quotes comes to the rescue past allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python3 para_str = """this is a long string that is made up of several lines and not-printable characters such as TAB ( \t ) and they will prove upwardly that manner when displayed. NEWLINEs inside the string, whether explicitly given like this within the brackets [ \n ], or merely a NEWLINE inside the variable assignment will also testify upwards. """ print (para_str)
When the above code is executed, it produces the following issue. Note how every unmarried special character has been converted to its printed grade, correct downwards to the last NEWLINE at the end of the cord between the "upward." and closing triple quotes. As well note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n) −
this is a long cord that is made up of several lines and not-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this inside the brackets [ ], or just a NEWLINE within the variable consignment will also show up.
Raw strings do not care for the backslash as a special grapheme at all. Every character y'all put into a raw string stays the way yous wrote it −
#!/usr/bin/python3 impress ('C:\\nowhere')
When the above lawmaking is executed, information technology produces the following consequence −
C:\nowhere
Now allow's make employ of raw string. We would put expression in r'expression' as follows −
#!/usr/bin/python3 print (r'C:\\nowhere')
When the above code is executed, it produces the following result −
C:\\nowhere
Unicode String
In Python three, all strings are represented in Unicode.In Python ii are stored internally every bit viii-fleck ASCII, hence it is required to attach 'u' to make it Unicode. It is no longer necessary now.
Congenital-in String Methods
Python includes the following built-in methods to manipulate strings −
Sr.No. | Methods & Description |
---|---|
1 | capitalize() Capitalizes commencement letter of string |
2 | centre(width, fillchar) Returns a cord padded with fillchar with the original cord centered to a full of width columns. |
three | count(str, beg = 0,cease = len(cord)) Counts how many times str occurs in string or in a substring of string if starting index beg and ending index cease are given. |
four | 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 cord version of string; on error, default is to enhance a ValueError unless errors is given with 'ignore' or 'replace'. |
half dozen | endswith(suffix, beg = 0, end = len(cord)) Determines if string or a substring of string (if starting alphabetize beg and ending index end are given) ends with suffix; returns true if so and imitation otherwise. |
seven | expandtabs(tabsize = viii) Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided. |
8 | find(str, beg = 0 finish = len(cord)) Determine if str occurs in string or in a substring of string if starting index beg and ending alphabetize stop are given returns index if found and -1 otherwise. |
9 | index(str, beg = 0, end = len(cord)) Same as find(), but raises an exception if str not found. |
10 | isalnum() Returns true if string has at least 1 grapheme and all characters are alphanumeric and false otherwise. |
11 | isalpha() Returns true if string has at least ane character and all characters are alphabetic and false otherwise. |
12 | isdigit() Returns truthful if string contains only digits and false otherwise. |
13 | islower() Returns truthful if cord has at least 1 cased graphic symbol and all cased characters are in lowercase and false otherwise. |
14 | isnumeric() Returns truthful if a unicode string contains merely numeric characters and false otherwise. |
15 | isspace() Returns truthful if string contains just whitespace characters and false otherwise. |
16 | istitle() Returns truthful if string is properly "titlecased" and false otherwise. |
17 | isupper() Returns truthful if string has at least one cased character and all cased characters are in uppercase and false otherwise. |
xviii | join(seq) Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string. |
19 | len(cord) Returns the length of the string |
twenty | ljust(width[, fillchar]) Returns a space-padded cord with the original string left-justified to a total of width columns. |
21 | lower() Converts all uppercase letters in string to lowercase. |
22 | lstrip() Removes all leading whitespace in cord. |
23 | maketrans() Returns a translation tabular array to be used in translate function. |
24 | max(str) Returns the max alphabetical character from the cord str. |
25 | min(str) Returns the min alphabetical character from the cord str. |
26 | replace(quondam, new [, max]) Replaces all occurrences of one-time in string with new or at most max occurrences if max given. |
27 | rfind(str, beg = 0,terminate = len(string)) Same as find(), just search backwards in cord. |
28 | rindex( str, beg = 0, terminate = len(cord)) Same every bit index(), but search backwards in string. |
29 | rjust(width,[, fillchar]) Returns a space-padded string with the original string right-justified to a full of width columns. |
thirty | rstrip() Removes all trailing whitespace of string. |
31 | separate(str="", num=string.count(str)) Splits string co-ordinate 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('\north')) Splits cord at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed. |
33 | startswith(str, beg=0,cease=len(string)) Determines if string or a substring of string (if starting index beg and catastrophe index terminate are given) starts with substring str; returns true if so and false otherwise. |
34 | strip([chars]) Performs both lstrip() and rstrip() on string |
35 | swapcase() Inverts example for all letters in string. |
36 | title() Returns "titlecased" version of string, that is, all words brainstorm with uppercase and the rest are lowercase. |
37 | interpret(table, deletechars="") Translates string according to translation table str(256 chars), removing those in the del cord. |
38 | upper() Converts lowercase letters in string to uppercase. |
39 | zfill (width) Returns original string leftpadded with zeros to a full of width characters; intended for numbers, zfill() retains any sign given (less ane zero). |
40 | isdecimal() Returns true if a unicode string contains but decimal characters and false otherwise. |
Useful Video Courses
Video
Video
Video
Video
Video
Video
How To Add Letter To String Python,
Source: https://www.tutorialspoint.com/python3/python_strings.htm
Posted by: brottprajectow.blogspot.com
0 Response to "How To Add Letter To String Python"
Post a Comment