September 27, 2021    /    Viewed: 366    /    Comments: 0    /    Edit

Examples of how to check if a character from a string is a letter, a special character or a whitespace in python:

### Create a string in python

Let's create for example the following sentence:

````sentence = "   Hello World !"`
```

Note:

````type(sentence)`
```

returns

````str`
```

### Check character type

#### Check if a character is a letter

To check if a character is a letter, a solution is to use isalpha()

````"a".isalpha()`
```

gives

````True`
```

while

````"1".isalpha()`
```

gives

````False`
```

#### Check if a character is a number

To check if a character is a letter, a solution is to use isalpha()

````"1".isdigit()`
```

gives

````True`
```

while

````"a".isdigit()`
```

gives

````False`
```

#### Check if a character is a whitespace

To check if a character is a letter, a solution is to use isalpha()

````"a".isalpha()`
```

gives

````True`
```

#### Check if a character is a special character

To check if a character is a special character, a solution is to check if it is not a letter, a number or a whitespace:

````if not ("!".isalpha() or "!".isdigit() or "!".isspace()):`
`        print("It is a special character")`
```

gives

````It is a special character`
```

Another solution is to define a list of special characters:

````sc_list = list('[@_!#\$%^&*()<>?/\|}{~:]')`

`c = '!'`

`if c in sc_list:`
`         print("It is a special character")`
```

gives also

````It is a special character`
```

#### Iterate over characters

````for c in sentence:`
`    print(c)`
```

gives

````H`
`e`
`l`
`l`
`o`

`W`
`o`
`r`
`l`
`d`

`!`
```

Now let's iterate over each character and check the type:

````for c in sentence:`
`    if c.isalpha(): `
`        print("character '{}' is a letter".format(c))`
`    else:`
`        if c.isdigit(): `
`            print("character '{}' is a number".format(c))`
`        else:`
`            if c.isspace(): `
`                print("character '{}' is a space".format(c))`
`            else:`
`                print("character '{}' is a special character".format(c))`
```

gives then

````character ' ' is a space`
`character ' ' is a space`
`character ' ' is a space`
`character 'H' is a letter`
`character 'e' is a letter`
`character 'l' is a letter`
`character 'l' is a letter`
`character 'o' is a letter`
`character ' ' is a space`
`character 'W' is a letter`
`character 'o' is a letter`
`character 'r' is a letter`
`character 'l' is a letter`
`character 'd' is a letter`
`character ' ' is a space`
`character '!' is a special character`
```  ##### Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!