Iván Chillón
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # PRO-UT1-A13. Ejercicios cadenas caracteres ## Actividades ### 1. Intercambio de carácteres extremos Escribe un programa en el que dada una cadena se genera una de salida en la que se intercambian el primer y último carácter de la misma. Usar subcadenas. ``` `vestimenta` -> 'aestimentv' ``` Solución: ```python cadena = input("Introduce texto: ") resultado = cadena[-1] + cadena[1:-1] + cadena[0] print(resultado) ``` ### 2. Sustituir repeticiones del primer carácter Escribe un programa en el que leamos una cadena de texto y devuelva cadena igual a la original, pero todas las repeticiones del primer carácter sean sustituidas por una "#" excepto el primer carácter. Usar subcadenas. ``` 'anónimamente' -> anónim#mente ``` Solución: ```python cadena = input("Introduce texto: ") primero = cadena[0] l = len(cadena) resultado = cadena for i in range(1,l): if cadena[i] == primero: resultado = resultado[:i] + "#" + resultado[i + 1:] print(resultado) ``` ### 3. Caracteres que ocupan posiciones pares Escribe un programa que genere una cadena con todos los carácteres que ocupan la posición par de una cadena y otra con los que ocupan la posición impar: ``` 'cadena perpetua' -> 'aeapreu', 'cdn epta' ``` Solución: ```python ``` ### 4. Intercambio de palabras Escribe un programa en Python al que le pasamos una cadena formada por dos palabras separadas por un espacio y genere una cadena en la que se intercambien las palabras ``` 'uno dos' -> 'dos uno' ``` Solución: ```python cadena = "primera segunda" aux = cadena.split() reversed = aux[::-1] cadena = " ".join(reversed) print(cadena) ``` ### 5. Separar y ordenar alfabéticamente Escribe un programa en el que leemos una cadena que contiene palabras separadas por comas y las muestra ordenadas alfabéticamente ``` `uno, dos, tres, cuatro` -> 'cuatro, dos, tres, uno' ``` Solución: ```python cadena = 'uno, dos, tres, cuatro' aux = cadena.split(", ") aux.sort() cadena = ", ".join(aux) print(cadena) ``` ### 6. Palabras que empiezan por a Escribe un programa al que le pasamos una cadena de caracterers y muestra las palabras que comiencen con la letra 'A'. Por ejemplo, si recibe 'Antes de ayer' debe devolver 'Antes ayer'. Solución: ```python cadena = 'Antes de ayer y despues de mañana ahora' aux1 = cadena.split() aux2 = [] for palabra in aux1: if palabra.startswith("a") or palabra.startswith("A"): aux2.append(palabra) cadena = " ".join(aux2) print(cadena) ``` ### 7. Caracteres distintos Escribe un programa en python al que le pasemos una cadena y muestre los caracteres distintos que incluye y cuantas veces se repite cada uno Solución: ```python cadena = 'Antes de ayer y despues de mañana ahora' aux = cadena.lower() l_encontrados = [] for caracter in aux: if caracter not in l_encontrados: print(f"{caracter} aparece {aux.count(caracter)} veces") l_encontrados.append(caracter) ``` ### 7.2. Capitalizar frases Escribir programa que pase a mayúscula la primera letra de cada frase de un texto. Las frases están separadas por puntos "." ```python cadena = ''' the Zen of Python, by Tim Peters. beautiful is better than ugly. explicit is better than implicit. simple is better than complex. ''' ``` Solución: ```python ``` ### 8. Función sin puntuación Escribe una función en Python a la que le pasamos una cadena de texto y devuelve la misma cadena, pero sin ningún signo de puntuación Solución: ```python ``` ### 9. Palabras distintas Escribe un programa al que le pasamos una cadena de caracteres que contiene una o varias frases y nos muestra todas las palabras que contiene y cuantas veces se repite cada una. **Nota:** las palabras pueden estar separadas por espacios o por signos de puntuación (',', '.', ';'). Solución: ```python ``` ### 10. Palíndroma Escribir una función que reciba una cadena y devuelva `True` si es palíndroma 'Daba la sal al abad' es palíndroma porque si eliminamos todos los espacios y pasamos todos los carácteres a minúsculas se lee igual de derecha a izquierda que de izquierda a derecha. 'dabalasalalabad' Solución: ```python ``` ### 11. Extraer número de teléfono Los teléfonos de una empresa tienen el siguiente formato prefijo-número-extension donde el prefijo es el código del país +34, y la extensión tiene dos dígitos (por ejemplo +34-928724710-56). Escribir un programa que pregunte por un número de teléfono con este formato y muestre por pantalla el número de teléfono sin el prefijo y la extensión. Solución: ```python ``` ## Complementarios ### 12. Transformar cadena Transformar una cadena de texto en función de unas reglas: * El primer carácter indica el número de veces que se repite la primera subcadena. Puedes suponer sólo números del 1 al 9. * El último carácter indica el número de veces que se repite la última subcadena. Puedes suponer sólo números del 1 al 9. * Las dos subcadenas de entrada están separadas siempre por un guión medio. * Las dos subcadenas de salida deberán estar separadas por una almohadilla. * No se puede usar el método `split()` ``` 2car-bike3' -> 'carcar#bikebikebike' ``` Solución: ```python ``` ### 13. Estraer fecha Escribir un programa que pregunte al usuario la fecha de su nacimiento en formato dd/mm/aaaa y muestra por pantalla, el día, el nombre del mes ('enero' por ejemplo) y el año. Adaptar el programa anterior para que también funcione cuando el día o el mes se introduzcan con un solo carácter. Solución ```python ``` ### 14. Informaciones de cadena Crea un programa python que lea una cadena de caracteres y muestre la siguiente información: * La primera letra de cada palabra. Por ejemplo, si recibe 'Universal Serial Bus' debe devolver 'USB'. * Dicha cadena con la primera letra de cada palabra en mayúsculas. Por ejemplo, si recibe 'república argentina' debe devolver 'República Argentina'. Solución ```python ``` ## Recursos * [https://www.w3resource.com/python-exercises/string/](https://www.w3resource.com/python-exercises/string/) * [https://pynative.com/python-string-exercise/](https://pynative.com/python-string-exercise/) * [https://www.geeksforgeeks.org/python-string-exercise/](https://www.geeksforgeeks.org/python-string-exercise/) * [https://www.pythonprogramming.in/strings.html](https://www.pythonprogramming.in/strings.html) * [https://www.codesdope.com/practice/python-string/](https://www.codesdope.com/practice/python-string/) * [https://exercism.org/tracks/python/exercises](https://exercism.org/tracks/python/exercises) ###### tags: `pro` `ut1` `cadenas` `ejercicios`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully