Основные методы строк

Syntax

The syntax for the isalpha function in the C Language is:

int isalpha(int c);

Parameters or Arguments

c
The value to test whether it is alphabetic.

In the C Language, the required header for the isalpha function is:

#include <ctype.h>

In the C Language, the isalpha function can be used in the following versions:

ANSI/ISO 9899-1990

isalpha Example

/* Example using isalpha by TechOnTheNet.com */

#include <stdio.h>
#include <ctype.h>

int main(int argc, const char * argv[])
{
    /* Define a temporary variable */
    unsigned char test;

    /* Assign a test letter to the variable */
    test = 'T';

    /* Test to see if this is a alphabet character */
    if (isalpha(test) != 0) printf("%c is in the alphabet\n", test);
    else printf("%c is not in the alphabet\n", test);

    /* Assign a non-alphabetic character to the variable */
    test = '7';

    /* Test to see if this is a alphabet character */
    if (isalpha(test) != 0) printf("%c is in the alphabet\n", test);
    else printf("%c is not in the alphabet\n", test);

    return 0;
}

When compiled and run, this application will output:

T is in the alphabet
7 is not in the alphabet

Similar Functions

Other C functions that are similar to the isalpha function:

  • isalnum function <ctype.h>
  • islower function <ctype.h>
  • isupper function <ctype.h>

Other C functions that are noteworthy when dealing with the isalpha function:

isascii method

As the name of the method suggests, this method checks whether the string contains ASCII characters, i.e checks whether the string is printable or not.

Syntax of method

This method has been newly introduced in Python version 3.7 and following is the syntax for it,

This method doesn’t take any parameters and the string refers to the input string which is checked for the presence of ASCII characters.

It returns True if the string is empty or if all the characters in the string are ASCII characters. Otherwise, it returns False. ASCII characters refer to characters that have a printable representation. Their code points lie between the range U+0000 to U+007F.

For example, is changed to Below is the code demonstrating how the degree symbol outputs as a string.

Output:

"'\\xb0'"
str

Time for an example:

Output:

True
True
True
True
False
False

isalnum method

The method can be called as an extension of the method. In addition to checking for the presence of alphabets in the string, the method checks whether the method contains numeric characters too. The method checks for the presence of alphanumeric characters(alphabets + numbers only).

Syntax of the method

Just like the method, the string here refers to the string which is being checked for containing alphanumeric characters or not.

This method also doesn’t take any parameters.

It returns True or False depending on the characters present the string.

In the below code, it can be observed that the method only approves for alphabets and numbers in a string. No special characters and white spaces are entertained.

Output:

True
False
False
True

isalpha Example

/* Example using isalpha by TechOnTheNet.com */

#include <stdio.h>
#include <ctype.h>

int main(int argc, const char * argv[])
{
    /* Define a temporary variable */
    unsigned char test;

    /* Assign a test letter to the variable */
    test = 'T';

    /* Test to see if this is a alphabet character */
    if (isalpha(test) != 0) printf("%c is in the alphabet\n", test);
    else printf("%c is not in the alphabet\n", test);

    /* Assign a non-alphabetic character to the variable */
    test = '7';

    /* Test to see if this is a alphabet character */
    if (isalpha(test) != 0) printf("%c is in the alphabet\n", test);
    else printf("%c is not in the alphabet\n", test);

    return 0;
}

When compiled and run, this application will output:

T is in the alphabet
7 is not in the alphabet

Triple Quotes

Python’s triple quotes comes to the rescue by 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/python

para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets , or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str

When the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the «up.» and closing triple quotes. Also 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 string that is made up of
several lines and non-printable characters such as
TAB (    ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets , or just a NEWLINE within
the variable assignment will also show up.

Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it −

#!/usr/bin/python

print 'C:\\nowhere'

When the above code is executed, it produces the following result −

C:\nowhere

Now let’s make use of raw string. We would put expression in r’expression’ as follows −

#!/usr/bin/python

print r'C:\\nowhere'

When the above code is executed, it produces the following result −

C:\\nowhere

String Formatting Operator

One of Python’s coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C’s printf() family. Following is a simple example −

#!/usr/bin/python

print "My name is %s and weight is %d kg!" % ('Zara', 21)

When the above code is executed, it produces the following result −

My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which 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 functionality are listed in the following table −

Symbol Functionality
* 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’ were used.
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.)

isalpha method:

In Python, the method is a built-in function and it checks for the presence of alphabets-only in a string. If all the characters in the string are alphabets, it returns . If the string contains other characters apart from alphabets for example a number or any special characters, it returns . Alphabets in the English language include characters from A-Z and a-z.

Syntax of the method

Here the string refers to the string in question, i.e the string which is being checked for containing only alphabets or not.

It doesn’t take any parameters.

It returns True or False depending on the characters inside the string. There should at least be one character inside the string for the method to evaluate the string. Look at the below code example to understand the use of this function:

Output:

True
False
False
False
False

Note: Whitespaces, numbers and special characters are not considered as alphabets.

SYNOPSIS top

       #include <ctype.h>

       int isalnum(int c);
       int isalpha(int c);
       int iscntrl(int c);
       int isdigit(int c);
       int isgraph(int c);
       int islower(int c);
       int isprint(int c);
       int ispunct(int c);
       int isspace(int c);
       int isupper(int c);
       int isxdigit(int c);

       int isascii(int c);
       int isblank(int c);

       int isalnum_l(int c, locale_t locale);
       int isalpha_l(int c, locale_t locale);
       int isblank_l(int c, locale_t locale);
       int iscntrl_l(int c, locale_t locale);
       int isdigit_l(int c, locale_t locale);
       int isgraph_l(int c, locale_t locale);
       int islower_l(int c, locale_t locale);
       int isprint_l(int c, locale_t locale);
       int ispunct_l(int c, locale_t locale);
       int isspace_l(int c, locale_t locale);
       int isupper_l(int c, locale_t locale);
       int isxdigit_l(int c, locale_t locale);

       int isascii_l(int c, locale_t locale);

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       isascii():
           _XOPEN_SOURCE
               || /* Glibc since 2.19: */ _DEFAULT_SOURCE
               || /* Glibc versions <= 2.19: */ _SVID_SOURCE

       isblank():
           _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L

       isalnum_l(), isalpha_l(), isblank_l(), iscntrl_l(), isdigit_l(),
       isgraph_l(), islower_l(), isprint_l(), ispunct_l(), isspace_l(),
       isupper_l(), isxdigit_l():
           Since glibc 2.10:
                  _XOPEN_SOURCE >= 700
           Before glibc 2.10:
                  _GNU_SOURCE

       isascii_l():
           Since glibc 2.10:
                  _XOPEN_SOURCE >= 700 && (_SVID_SOURCE || _BSD_SOURCE)
           Before glibc 2.10:
                  _GNU_SOURCE

Удаление элементов в кортеже

Удаление отдельных элементов в кортежей не представляется возможным. Кортеж с нежелательными элементами отбрасывается.

Чтобы явно удалить весь кортеж, просто используйте заявление del. Например:

#!/usr/bin/python3

tup = ('andreyex', 'chemistry', 2017, 2010);

print (tup)
del tup;
print "После удаления tup : "
print tup

Это приводит к следующему результату:

Примечание:
Вызвало исключение. Это происходит потому, что после того, как запустилась команда del tup на выполнение, кортеж не существовал.

('andreyex', 'chemistry', 2017, 2010)
After deleting tup :
Traceback (most recent call last):
   File "test.py", line 9, in <module>
      print tup;
NameError: name 'tup' is not defined
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector